Saturday, 29 November 2014

Some Interesting Questions in iOS

1. Why we use auto layout in place of autoresize ?
Ans.  The main reason for this is that in auto layout we can have parent child relationship between views .

2. Categories over sub classing ?
Ans. If we use subclassing then we need to implement all the methods and then we can add methods to the child class but in Categories there is no overhead of implementing all the methods you can only add methods to the class .

3. If we add a protocol to a class and didn't implemented in .m file what will happen ?
Ans. Once added to the interface of a class the class will always confirm to the protocol , to check weather the class has the particular method we can use a method performSelector on the object.

4. When we use delegations and notifications ?
Ans. If we have related objects only then we use delegations for unrelated objects we use notifications

5. Keyword Assign
Ans. The assign will point to the object and we have take care to make it nil or it will become dangling pointer , if we use strong keyword then when the object is released the value is set to nil once the object is deallocated.

6. Operation queue VS GCD ?
Ans. In GCD we can't add or join operations . And dispatch queues are First In First Out.

7. Why we should use AFNetworking Framework ?

Ans. While NSURLConnection provides +sendAsynchronousRequest:queue:completionHandler: and+sendSynchronousRequest:returningResponse:error:, there are many benefits to using AFNetworking:
  • AFURLConnectionOperation and its subclasses inherit from NSOperation, which allows requests to be cancelled, > suspended / resumed, and managed by an NSOperationQueue.
  • AFURLConnectionOperation also allows you to easily stream uploads and downloads, handle authentication challenges, > monitor upload and download progress, and control the caching behavior or requests.
  • AFHTTPRequestOperation and its subclasses distinguish between successful and unsuccessful requests based on HTTP > status codes and content type.
  • AFNetworking includes media-specific request operations that transform NSData into more useable formats, like JSON, > XML, images, and property lists.
  • AFHTTPClient provides a convenient interface to interact with web services, including default headers, authentication, > network reachability monitoring, batched operations, query string parameter serialization, and multipart form requests.
  • UIImageView+AFNetworking adds a convenient way to asynchronously loads images.
8. Dispatch Queue vs Threads.
Ans.
1. The major advantage of using dispatch queues is that you can focus on the work that need to be performed as compared to the thread where you need to focus on both work and thread creation. 
2.The system can scale it dynamically based on the current condition of resources .
3.




Wednesday, 12 November 2014

Memory Management in Objective C

Stack
The stack is a region of memory which contains storage for local variables, as well as internal temporary values and housekeeping. On a modern system, there is one stack per thread of execution. When a function is called, a stack frame is pushed onto the stack, and function-local data is stored there. When the function returns, its stack frame is destroyed. All of this happens automatically, without the programmer taking any explicit action other than calling a function.

Heap
The heap is, essentially, everything else in memory. (Yes, there are things other than the stack and heap, but let's ignore that for this discussion.) Memory can be allocated on the heap at any time, and destroyed at any time. You have to explicitly request for memory to be allocated from the heap, and if you aren't using garbage collection, explicitly free it as well. This is where you store things that need to outlive the current function call. The heap is what you access when you call malloc and free

Copy
The copy in objective C is used to save a state of an object . It's generally used when an object have multiple owners and you are willing to save its current value. (Used for Mutable Objects)

Assign
The assign will generate a setter with assigns the value to the instance variable  directly, rather then copying or retaining it. This is best for primitive type like NSInteger and CGFloats or objects you don't own like delegates . 

The assign basically creates a weak pointer to the object and you need to make it nil or else it may become dangling pointer. 

Friday, 7 November 2014

Blocks in Objective C.

Blocks are Objective-C’s anonymous functions. They let you pass arbitrary statements between objects as you would data, which is often more intuitive than referencing functions defined elsewhere.

Note: "Blocks are created on stack and hence they will be released as the function call gets over. You need to copy block if you wish to sustain its data."

Blocks are similar to the functions in objective C.

In 3 simple Steps:


1. Declaration
// Declaration a Block
    int (^calculate)(int a, int b);

2. Definition

// Define
    calculate= ^int(int a, int b)
    {
        return a+b;
    };

3. Calling

    NSLog(@"sum is %d",calculate(5,6));

The '^' caret symbol is used to notify the complier that the calculate is a block .
So a block will have

1. Return type
2. Name
3. Variable

If we don't want that our block will have return type or params then we need to replace it with void.

// with return type and params
     int (^sum)(int a);

// without params
     int (^sum)(void);

// without params and return type

     void (^sum)(void);

Now we will work in details with block return type and params. 

//    Either This 
    void (^sum1)(int a)= ^void(int a){
         //  Some Code ....
    };
//   Or This both will differ is syntax only

    void (^sum1)(int a);

    sum1= ^void(int a)
    {
         // Some Code ...
    };
Specifying the return type of a block is always optional .

    int (^sum2)(void)= ^int(void)
    {
        
        NSLog(@"I am in block 2");
        return 4;
    };
    
    void (^sum4)(void)=^ {
        
        NSLog(@"I am in sum 4");
    };



In the above 2 examples if we don't produce the return type then it won't affect anything. It's also known as PARAMETER LESS blocks.
==
Blocks are implemented as closures which means they can have access of local and non local variables. 

For e.g. 

NSString *make = @"Honda";
NSString *(^getFullCarName)(NSString *) = ^(NSString *model) {
    return [make stringByAppendingFormat:@" %@", model];
};
NSLog(@"%@", getFullCarName(@"Accord"));    // Honda Accord

In the above example the "getFullCarName" is the block name and it has NSString as param and return type.
In the definition of the block we skipped the return type as it's purely optional and our param i.e. (NSString * model ) will be a local variable for block.
In the above example the "make" is non local variable and model is local and we are using both.

By default the variables are copied to the block and they are readonly. 

If you are willing to change the value of non local variables in the block you have to mentioned this in the variable declaration explicitly.

_ _ block NSString * myString =@"car";

Passing blocks as an argument of a function.

let us suppose a scenario .

There is a model class named Person and its has attributes age and height.

We have defined a block which will take an integer as a param and returns nothing


typedef void (^testBlock)(int b);

There is a instance function  which take block as a parameter.

-(void)calculateHeightUsingBlock:(testBlock)heightActivity;

In the .M file of this class we have mentioned its details 

 // Here ' heightActivity ' is the name variable for 'testBlock' and if you want to send control back to the calling place you need to call the block as did in the last line 'heightActivity(5)'

-(void)calculateHeightUsingBlock:(testBlock)heightActivity  
{
    NSLog(@"I am in calculate HEIGHT Block Class and height= %d",self.height);
    heightActivity(5); // this will execute the body written in the calling place.
}

Once you write the statement heightActvity(5), The control will go back from where this block is called and the body of block will be executed. 

// Now calling this block from a view controller

- (void)viewDidLoad

{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    Person * newPerson= [[Person alloc]init];
    newPerson.height=7;
    newPerson.age=40;
    
    [newPerson calculateHeightUsingBlock:^(int a) 
   {
        
        NSLog(@"I am in ViewController Block for Height %d",a);
    }];
// If you debug your code the control of a function will go back to the new person class as its a normal function call and once the task code of the Person class is executed then the control will be handover to the ViewController class and the Log statement will be executed. 
}
Here we are having call backs without using delegations. This is the beauty of blocks !!!.

Ref:
1. http://iosdevblog.com/
2. Block memory related: http://www.friday.com/bbum/2009/08/29/blocks-tips-tricks/