Tuesday, July 7, 2015

Objective C Concepts Learning

Objective C Blocks

What is Block;

Block is an anonymous function in Objective C.

Blocks can be used as below:

As a local variable:
returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};

As a property:
@property (nonatomic, copy) returnType (^blockName)(parameterTypes);

As a method parameter:
- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;

As an argument to a method call:
[someObject someMethodThatTakesABlock:^returnType (parameters) {...}];

As a typedef:
typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters) {...};


Important Concepts of Blocks

-          Blocks will freeze the variables which are accessed from outside the block. It will make the variable as constant with the value assigned to it.

 NSString *variable = @"Madhavan";

-          To allow blocks to make the variable as mutable we need to declare as below

__block NSString *variable = @"Madhavan";

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Use of @ in Objective C

@ is a keyword used to differentiate Objective C keywords from C or C++ keywords.


@ symbol tell the compiler it is as Objective C construct and not the C or C++ construct.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Autoreleasepool in Objective C

autoreleasepool is used to retain or release the object created by the developer. Whenever the loop increaments the autorelease pool make the reference count +1 and -1 when the loop finish the task.

No comments: