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

What does enable bitcode do in Xcode

Background: Now days compilation process for any language is divided into two parts and same is applicable for objective c. Frontend Compiler (Clang) Backend Compiler (LLVM) Frontend Compiler (Clang):  Responsibility of front-end compiler is to take a source code and convert into intermediate representation (IR).  In case of clang it is LLVM IR.  Backend Compiler(LLVM):  Responsibility of backend compiler is to take a IR as input and convert into object code. LLVM input is bitstream of LLVM IR (Bitcode) and output is sequence of machine instruction(Object code). Each  cpu or processor has different set of  M achine   instruction, So  LLVM output is CPU dependent or it can be executed on specific CPU only.   There may be question in your mind that  1) What is the need to divide into these phases? 2) What is LLVM IR? Can we see the LLVM IR as Output? What is the need to divide into these phases? It is beneficial for both the programming language designer a

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 Handler class

Everything about BLE with iOS Part1 (Introduction)

In this article we will learn how to turn your iPhone to behave as peripheral (who has data to send) or central (who receive the data). What is BLE (Bluetooth Low energy device) ? Bluetooth LE is a wireless personal area network technology like its previous incarnation, Classic Bluetooth. It can be use to transfer and receiving of the data. What is difference between Classic and LE ? BLE has low power consumption and low data transfer rate. BLE can support large number of slaves. On the other hand Classic (3.0) support maximum 7 devices connectivity. Unique feature of BLE is advertising  functionality,  So other devices can scan,  connect and  receive data from the advertising BLE device. Other difference is in classic you need to pair the devices first for the communication. Terms: Peripheral:  It is device which advertise the service. In client-server architecture form we can say peripheral is server which has data to send to client. The basic difference i