How to use Object C in IOS?
Objective C is used in iOS development. It is built on top of the C programming language and offers object-oriented capabilities and a dynamic runtime. It includes all familiar elements like primitive types i.e. int, float, char, etc. structures, pointers, functions, and control flow constructs.
You can also use standard C library routines which are declared in stdlib.h and stdio.h. In the interface file class is declared and in the implementation file class is defined.
Suppose there is a class IntellipaatClass.h then its interface file is:
@interface IntellipaatClass:NSObject { // Declaration of class variable } // Declaration of class properties // Declaration of class methods and instance methods @end
The implementation file IntellipaatClass.m is as follows:
@implementation IntellipaatClass // Class methods @end
Methods
In Objective C method is declared as follows –
-(returnType)Method_Name:(type_Name) variable1 :(type_Name)variable2;
Create Object
In Objective C objects are created as follows:
IntellipaatClass *object_Name = [[IntellipaatClass alloc]init] ;
Class methods do not contain any objects and variables related with it. They can be accessed directly without creating objects for the class. Example is as follows:
+(void)Class_Method;
It can be accessed by using the class name like as follows −
[IntellipaatClass ClassMethod];
Instance methods – It can be accessed only after creating an object for the class. Memory is allocated to the instance variables.
-(void)InstanceMethod;
They can be access after creating an object like as follows –
IntellipaatClass *objectName = [[IntellipaatClass alloc]init] ; [objectName InstanceMethod];
Example
#import <Foundation/Foundation.h> @interface SampleClass:NSObject -(void)sampleMethod; @end @implementation SampleClass -(void)sampleMethod{ NSLog(@"Hello, World! n"); } @end int main() { /* my first program in Objective-C */ SampleClass *sampleClass = [[SampleClassalloc]init]; [sampleClasssampleMethod]; return 0; }
Objects Communicate Through Messages
In Objective C one object sends a message to another object by calling a method on that object. If you have an object somePerson of class XYZPerson, you can send it the sayHello message like this:
Syntax:
[somePerson sayHello];