Skip to main content

Best Practices in iOS with Objective - C


In this post i am making collection of points which i read from some other post or some documentation. Today we will learn what are good or bad habits while doing programming in objective - c.

1) Instance Type and id

I noticed one day that in iOS SDK init method of class has instancetype as a return value. I am curious to know about this thing and why this type not id. So what i found is following:

Example:

- (instancetype)initWithProximityUUID:(NSUUID *)proximityUUID identifier:(NSString *)identifier

What is instancetype?

Suppose you are writing a method for object initialisation and according to objective c coding convention you need to return the object of same class from the method. So you can use instance type as a return type of method.

Instance Type -  It represents the instance of the class or subclass of the class in which you are writing the method with return type instancetype.

Confusing ?

Let suppose i have declare a class employee with init method init with id like below:
- (instancetype)initWithEmployeeId:(NSString *)ID

Here instance type refer to the instance of class employee or sub class of employee. Like if i have temporary employee as subclass of employee then instance type can be used to represent that.

Why to use instance type we can use id as well?

Type Safe - It improves the type safety. If you calling a method on the return type of  the method the compiler will check whether object respond to the method if not then generate a warning. In case of id there will be no type check and no warning if object do not responds to method.

So where is the more chances of crash ?
Obviously id as no checking at compile time so crash at run time. So use type safe in your code.

Example:

@interface Encryption : NSObject

+ (instancetype)objectWithMD5key:(NSString*)key;
+ (id)objectWithShaiKey:(NSString*)key;


@end

Try to initialise the object by following lines and result is as given below:  

NSUInteger encObject = [[Encryption objectWithMD5key:@"test"] count]; // Compiler warning No visible @interface for 'Encryption' declares the selector 'count'
NSUInteger enc1 = [[Encryption objectWithShaiKey:@"test"] count];  // Work without error

So with instance type we can add type safety in our code.

2) Reference of UIApplication Delegate

There is always recommendation in the apple coding guidelines that do not use app delegate reference in your code. One day i am listening to the WWDC session for camera controller. In which they clearly say that do not use application delegate reference in your code.

First let understand how we are using application delegate reference in our code:

Let i have created sample application with name "Sample" and i have app delegate object  with name "Appdelegate" in my application. Following is the code line which create the reference for the app delegate.

AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

So always try to not to take the reference of application delegate in your code. We all know it is simple and easy way when we require communication between to unknown objects . But it is not good coding practice to use that. 

Bad Effects :

1) Break the rule High Cohesion and Low Coupling:

We should design our class in such manner that it should follow high cohesion and low coupling i.e. the functionality in a class has common activities or related activities. So according to this rule a component should do one work and do it well.

Like i have a component in my application HTTP connection which has the functionality to make url request and provide the result to other module. What happen if the module also parse the data and store it in database. If any change request happen to database then we also need to change the Http connection module.

This is the example of High coupling. So in this manner our app delegate is only responsible to do task for application event. We should not give the burden to this object to handle communication and keep the data for other objects.

More Detail:

2) Separation of Concern:

It is another design principle and according to that each interface should be designed in a way that overlap in the functionality as little as possible. In general term we can say that divide your application into distinct feature such that all the feature should exist independently.

Let us suppose you have application of news reader. Think about the feature set first. For me following are feature set i will divide the application into different function:

1) Http Connection module
2) Parser Module
3) UIViewController Module
4) Application Modal data (Keep the application data)

So now question is how this design principle break when we kept the other information in app delegate. Application delegate do not design to have responsibility act as manager or coordination manager and why it should keep other object which is not related to application event. 

The common mistake i have done when i need to refer to app delegate in my code is below:

1) Camera controller object in app delegate
2) Application modal object in app delegate

So what is the solution to avoid this

we can use following design principle.
1) Singleton Class.
2) Delegate Design pattern.

You can add more into this. Please provide your feedback on this. 

Comments

Popular posts from this blog

Asynchronous Request with NSOperationQueue

Today post is about how to run a asynchronous task in NSOperationQueue.  Generally we do not run a Asynchronous task in NSOperationQueue. It is also not recommended for any programmer to do that. This post is only for learning purpose what will happen if we schedule a asynchronous task in a queue and how can we complete that task:). So let us move to the learning: NSOperationQueue: In iOS NSOperationQueue is a class, which provide a way to perform operation concurrently. We also have others way to perform concurrent operation: 1) GCD 2) NSThread 3) pThread NSOperationQueue is a wrapper on GCD, which provides a very convenient way to execute operation concurrently. To create a Queue for Operation you have to simply allocate a object of the class: NSOperationQueue * opertionQueue = [[ NSOperationQueue alloc ] init ]; For this post let suppose you are making a queue to handle all Http request in your application. So i want to create a queue in Handl...

Shake Effect in iOS

Animation Animation always capture the user attention. We can use animation to update things on the screen.  For developer also animations fascinated things to learn and implement. Today we will try shake effect with Various  API. CABasicAnimation: Here we animate view's frame y coordinate from one position to another position. It is simple example of changing the position with respect to time. CABasic Animation is deal with the single keyframe.                                        y(t) = y 0 + t*d(y) You can use CABasic Animation if you have to play with single value. You need to move object from  one position to another without any intermediate steps. CABasicAnimation * shakeAnimation = [CABasicAnimation animationWithKeyPath: @ "position" ]; shakeAnimation . duration = 0.05 ; shakeAnimation . autoreverses = YES; shakeAnimation . repe...

NSThread with Asynchronous Request

NSThread: It is class used in Cocoa framework to create a thread.You have to specify a target and selector to create a new thread in objective c. So the selector or method is main entry point of your thread.  Detail: What happen once the thread execute all the code in the method (Thread main routine)? Thread is terminated after execute all the code in the entry(its main routine) routine. So how we can run an asynchronous request on NSThread ? What is Async request? It is non blocking request which permit the application to do other task side by side as request is in continue. So it enhance parallelism in the application. Now question is how we can prepare a asynchronous request in iOS: - ( void ) startAsyncRequestWithUrl:( NSString *)urlString{     assert (urlString != nil && urlString. length > 0 );     NSURL * url = [[ NSURL alloc ] initWithString :urlString];     NSURLRequest * urlRequest = [[ NSURLReq...