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/  

Wednesday, 24 September 2014

Categories in iOS

Basic Definition:

Categories are wonderful feature of the Objective C language by using categories on a class we can expand the functionality of the class without touching it.

Analogy of category:

If you a smart phone (assume it as a base class) and you have some accessories of it like blue tooth earpiece (additional functionality)


                       

                                      Only Class                                  Class + Category.
                                        iPhone                                    iPhone + ear piece


Here we are not touching iPhone Class and adding functionality to the it that you can attend call from your earpiece.

So category will look like:

@interface iPhone (earPiece)
- (iPhone *)receiveCallFromBlueTooth:(BOOL)isEnabled;
@end

In the above syntax iPhone is class on which earPiece category is added.

Another Example:


We need to validate every email enter by the user every time and generally we don't have anything provided form apple and this situation come across several view controller and several projects .


An easy solution for this problem what i generally use create a category on NSString.


NSString+NSString_validateEmail.h
#import <Foundation/Foundation.h>

@interface NSString (NSString_validateEmail)
- (BOOL) isValidEmail:(NSString *)yourString;
@end

NSString+NSString_validateEmail.m
#import "NSString+NSString_validateEmail.h"

@implementation NSString (NSString_validateEmail)

- (BOOL) isValidEmail:(NSString *)yourString
{
    BOOL stricterFilter = YES; 
    NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
    NSString *laxString = @".+@([A-Za-z0-9]+\\.)+[A-Za-z]{2}[A-Za-z]*";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:checkString];

} 
@end

TO Call this function in your VC , you just need to import the class 

#import "NSString+NSString_validateEmail.h"
and while comparing 

 if(! [self isValidEmail: abc@xyz.com])
{
   // Alert the user if validation fails.
}

Here are some of the common concepts for categories that generally confuses us.

1. Why can't we add instance variable to the categories ?

Ans: The methods that are available in any category are added to any class at RUN Time only .

2. Difference between categories and class extension ?

Ans: Class extension is basically used to expand the public interface of the class with some private methods and properties

  • Its scope is local to a single class 
  • It added on the compile time only
  • Method added in the extension of a class should be implemented in the class

Ref:  http://just-works.blogspot.in/2013/11/subclass-category-and-extensions-in.html


Thursday, 31 July 2014

UDID for iOS 7

Form iOS 7 UDID is not available for public API so it can't be extracted from any of the applications available in the market.


If you are using iOS 6 then it can easily be found by downloading this application :
UDID + by eMonster

But for iOS 7 we need to connect the device from iTunes and from there we can extract the UDID of device. (If we still use the application then we will get UDID Starting from FFFFFF means a Fake UDID. )

Here is the process explained.

1. Connect the device and open the iTunes navigate to iPhone 




2. Then Click on the serial Number



3 . Right Click to Copy the UDID.













Tuesday, 27 May 2014

Delegations in iOS

Delegations - "Its basically a design pattern !!"

Link: Apple Docs for Delegations

You can download the source code here .

Let us suppose a scenario:

There is a View Controller which contains list of available restaurants near your location and now you want to filer the list of restaurants on basis of some parameters like nearby restaurants.

To achieve the above stated scenario what you will do is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@protocol myFilter <NSObject>

-(void)allNearRestos;
-(void)allFarRestos;
-(void)allRestos;

@end

// Protocol is defined above the import statment to avoid cyclic redundancy

#import <UIKit/UIKit.h>
#import "Resto.h"
#import "FilterViewController.h"
// #IMP

@interface ListOfRestosTVC : UITableViewController<UITableViewDataSource,UITableViewDelegate,myFilter> // Added myFilter protocol to this class.

@end

This is how your interface file looks like.

Now as a next step we will

1. Create A View Controller which contains list of restaurants. (ListOfRestoTVC)
2. Create another View Controller which contains the interface for parameters. (FilterViewController)
           -- Now you need filter the list of restaurants on the basis of filter applied--

Here comes the concept of delegations where you create a protocol (Filter Protocol) which have some methods in it .

Now your view controller will add this protocol and will implement it in your implementation file and you need to define all the required methods functionality in the implementation file.

The last step is while moving form main list of restaurants to the filter page you need to assign delegations stuff. 

What you will do is.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
   
    if ([[segue identifier] isEqualToString:@"filterVCSegue"])
    {
     
        FilterViewController * fvc= (FilterViewController*)segue.destinationViewController;
        // If you are using storyboards then please don't alloc init with the VC intitalization this won't work.
// #IMP
        fvc.myCustomDelegate=self;
        
        // myCustom Delegate is an 'id' type object and a property of filterviewcontroller class.
        // self means current class.
        // as a whole this statement means you are assigning the current class to the object of filter class and call call method of current class (i.e List of restaurents)
    }
}


Now we move on the Filter View Controller.

Here we will create one id type object who will confirm the protocol (myFilter)

@property (nonatomic,assign) id<myFilter>myCustomDelegate; 
// this object will follow myFilter protocol

As we have already assigned it while transiting from List to Filter View Controller. 

Now we can use all the protocol methods of List View Controller class with this delegate and can perform operations in the List VC  .



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
- (IBAction)allNear:(id)sender { // its an action for a button Clicked.
    
    NSLog(@"My Custom Delegate %@",_myCustomDelegate);
    
    [_myCustomDelegate allNearRestos];
    // Remeber we have assigned myCustomDelegate in prepare of Segue Method to SELF. As self was the ListOfRestoTVC so we can call methods AllNearREsto which is listed in the protocol only.
    
    [self dismissViewControllerAnimated:YES completion:nil];

}

The method "allNearRestos" is defined in ListView Controller and we are calling this method from FilterViewController.

This is how there 2 classes are connected and this is beauty of delegations.

You can download the source code here .

Cheers.

Monday, 19 May 2014

Process to Install the Application in iPhone Via iTunes.

I have mentioned the process to install the application signed in the development mode to the iPhone whose UDID was added in the provisioning profile.

Notes for the pictorial Steps
a. Red Color for process
b. Green Color for Information
c. If there are more then one thing to be done then Numberings will be done from starting from 1.

Here are pictorial steps to install the application through iTunes :

====================================================================================
Step 1 :


Step 2:


If Apps is not available in your iTunes you Directly Jump to Step 3 and add the files to the Library
(File--> Add to Library )

Step 3:


Step 4:


Step 5:


Step 6:


Step 7:



Step 8:





====================================================================================

Welcome

Hi All ,

I am Vinay Chopra a passionate mobile application developer. Here i am starting my first Blog and will share all the technical knowledge for others.

Welcome to my Blog. :)