Monday, July 15, 2013

Classes, Objects, and Methods in Objective c


As we know Objective-C  Support classes and objects. Objective-C is entirely different from C++ it have a strict object model, unlike C++. For instance, in Objective-C, classes are objects and can be dynamically managed: it is possible to addclasses at run-time, create instances based on the name of the class, ask a class for its methods, and so on.

An example Program in Objective C

#import Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   NSLog (@"IOS Tutorial");

   [pool drain];
   return 0;
}

In Objective C We have three sections to modify in object oriented concept.

  • Interface
  • Implementation
  • Program Section

//Interface Section

#import

@interface classname : NSObject
{
//define instance variables here

}

-(void ) print;
@end

//Implementation Section
@implementation classname

-(void) print
{
    NSLog(@"IOS Tutorial");
}
@end


// Program Section


int main (int argc, const char * argv[])
{
    NSAutoreleasePool pool = [[NsAutoreleasePool alloc] init];
    classname *aobject=[[classname alloc] init];
    [aobject print];
    [aobject release];
    [pool drain];
    return 0;
}

The @interface section


    It describes the class , its data components, and its methods, where the @implementation section contains the actual code that implements these methods.  Finally, the program section contains the program code to carry out the intended purpose of the program.

First, you have to tell the Objective-C compiler where the class came from.That is, you have to name its parent class.Second, you have to specify what type of data is to be stored in the objects of this class. That is, you have to describe the data that members of the class will contain.These members are called the instance variables. Finally, you need to define the type of operations, or methods, that can be used when working with objects from this class.This is all done in a
special section of the program called the @interface section.The general format of this section looks like this:

@interface NewClassName: ParentClassName
{
    memberDeclarations;
}
methodDeclarations;
@end

The @implementation Section


    As noted, the @implementation section contains the actual code for the methods you declared in the @interface section. Just as a point of terminology, you say that you declare the methods in the @interface section and that you define them (that is, give the actual code) in the @implementation section. The general format for the @implementation section is as follows:

@implementation NewClassName
methodDefinitions;
@end

No comments:

Post a Comment