Featured post

Difference between protocol and delegates?

A protocol, declared with the ( @protocol syntax in Objective-C) is used to declare a set of methods that a class "adopts" (de...

Friday, 10 June 2016

What is the difference between strong, retain, nonatomic, etc., in the Objective-C (iOS) property?

I've done a small bit of iOS work, so I might be able to cover the basics.  Strong and Weak help with retain-release cycles (RRC), a form of memory leak. iOS uses something called Automatic Reference Countin (ARC) to know when an object is in use and should be kept in memory, or is no longer in use and should be deleted to gain back resources. ARC works because the runtime knows for each object, how many objects are referencing it. When that found reaches 0, the object is deleted. 

Issues arise when you have two objects that hold references to each other. Because object A holds a reference to object B, and B to A, the reference count for both A and B will never be 0, this A and B will always be in memory. It's also possible that there are no other objects holding references to A or B, so we've just created a memory leak.

Getting back to Strong and Weak, these keywords are used to "denote ownership", if you will. They help you eliminate retain-release cycles by limiting what objects increment the reference count for another object. A strong property is one where you increment the reference count of the object. If object A has a strong reference to B, and no other object is referencing B, B has count 1 (A owns, or needs to exist B). Now, if B wants to have a reference to A, we would want to use a weak reference. Weak references don't increment the reference count of the object. So in this particular case, if A has no other objects referencing it but B, A's count would be 0 given B's weak reference.

Can you see how this is eliminating the RRS? Assuming no external references and not using strong/weak references, A and B would perpetually reside in memory. Using the strong and weak references we outlined above, A would have count 0, so it would be removed from memory. This in turn would deincrement B's reference count from 1 to 0, causing B to be removed from memory.

Nonatomic is used to denote that the object being referenced in not thread safe. This means that the object is not able to deal with multiple requests at the same time. Atomicity is the idea that once you make a request, it either happens or it doesn't. When an operation is atomic, you're guaranteeing that the entity you're applying the operation to will never be in an intermediate state. Regardless of how you look at that entity, it either looks the way it did before you requested the operation, or it looks the way it will once the operation is done. (When thinking about atomicity, think of atoms. The word means indivisible. Atomic operations are those which can't be divided into smaller operation

Monday, 6 June 2016

The Basics of Protocols and Delegates

 Apple offers a good overview of working with protocols in their Objective-C Programming Reference. However, sometimes a simple working example can go a long ways…
Introduction
Protocols can be helpful in a number of scenarios, a common usage is to define methods that are to be implemented by other classes. A familiar example is when using a tableview, your class implements the cellForRowAtIndexPath method which asks for cell content to insert into a table – the cellForRowAtIndexPath method is defined within the UITableViewDataSource protocol.
Let’s walk through a very simple example of defining and adopting a protocol.
Protocol Definition
Here is an example of a protocol which includes one method, notice the instance variable delegate is of type id, as it will be unknown at compile time the type of class that will adopt this protocol.
#import <Foundation/Foundation.h>
 
@protocol ProcessDataDelegate <NSObject>
@required
- (void) processSuccessful: (BOOL)success;
@end
 
@interface ClassWithProtocol : NSObject 
{
 id <ProcessDataDelegate> delegate;
}
 
@property (retain) id delegate;
 
-(void)startSomeProcess;
 
@end
Protocol Implementation
Inside the implementation section for the interface defined above we need to do two things at a minimum – first synthesize the delegate instance variable and second, call the method defined in the protocol as needed (more on that in a moment).
Let’s look at a bare bones implementation of the ClassWithProtocol.m:
#import "ClassWithProtocol.h"
 
@implementation ClassWithProtocol
 
@synthesize delegate;
 
- (void)processComplete
{
  [[self delegate] processSuccessful:YES];
}
 
-(void)startSomeProcess
{
  [NSTimer scheduledTimerWithTimeInterval:5.0 target:self 
    selector:@selector(processComplete) userInfo:nil repeats:YES];
}
 
@end
Understand this is a rather contrived example – the intention is to show how/where one might use a protocol. For the sake of discussion assume you have a class that is processing (or downloading) some type of data. Further, assume this class is called from another class to begin the processing. Chances are, at some point the caller will want to be notified that the class processing the data is done, this is where the protocol comes in.
In the calling class, the method defined in the protocol, processSuccessful, will be implemented and will be called from the object doing the processing, once it is complete.
For this example, inside the class where the protocol is defined, I have one method,startSomeProcess, which simply starts a timer and calls processComplete after 5 seconds. Inside processComplete the calling object will be notified through its delegate that the process is done.
Adopting the Protocol
To keep the example short, I am using the applicaton delegate as the class that adopts the protocol. Here is how the app delegate looks:
#import <UIKit/UIKit.h>
#import "ClassWithProtocol.h"
 
@interface TestAppDelegate : NSObject <UIApplicationDelegate, ProcessDataDelegate>
{
  UIWindow *window;
  ClassWithProtocol *protocolTest;
}
 
@property (nonatomic, retain) UIWindow *window;
 
@end
A few things to note – ProcessDataDelegate is defined as part of the interface, which signifies that this class will adhere to the protocol. Looking back to the code for defining the protocol, notice that I added @required to the definition, which means that any class that adopts the protocol must implement the processSuccessfulmethod (you will receive a compile warning if you don’t).
Here is the implementation of the app delegate and the required method for the protocol:
#import "TestAppDelegate.h"
#import "ClassWithProtocol.h"
 
@implementation TestAppDelegate
 
@synthesize window;
 
 UITableViewDelegate
 
- (void)processSuccessful:(BOOL)success;
{
  NSLog(@"Process completed");
}
 
- (void)applicationDidFinishLaunching:(UIApplication *)application 
{   
  // Create and initialize the window
  window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
 
  protocolTest = [[ClassWithProtocol alloc] init];
  [protocolTest setDelegate:self];
  [protocolTest startSomeProcess];
 
  [window makeKeyAndVisible];
}
 
- (void)dealloc 
{
  [window release];
  [super dealloc];
}
 
@end
How it all works
Things goes as follows: the app delegate will create a new instance of theClassWithProtocol object. It sets itself as the delegate and then calls thestartSomeProcess method. At some point in the future, when the protocolTestobject has completed its work – after the 5 second timer has fired – it will call theprocessSuccessful method in the app delegate to let it know it is done processing.
Protocol Implementation
Inside the implementation section for the interface defined above we need to do two things at a minimum – first synthesize the delegate instance variable and second, call the method defined in the protocol as needed (more on that in a moment).
Let’s look at a bare bones implementation of the ClassWithProtocol.m:
#import "ClassWithProtocol.h"
 
@implementation ClassWithProtocol
 
@synthesize delegate;
 
- (void)processComplete
{
  [[self delegate] processSuccessful:YES];
}
 
-(void)startSomeProcess
{
  [NSTimer scheduledTimerWithTimeInterval:5.0 target:self 
    selector:@selector(processComplete) userInfo:nil repeats:YES];
}
 
@end
Understand this is a rather contrived example – the intention is to show how/where one might use a protocol. For the sake of discussion assume you have a class that is processing (or downloading) some type of data. Further, assume this class is called from another class to begin the processing. Chances are, at some point the caller will want to be notified that the class processing the data is done, this is where the protocol comes in.
In the calling class, the method defined in the protocol, processSuccessful, will be implemented and will be called from the object doing the processing, once it is complete.
For this example, inside the class where the protocol is defined, I have one method,startSomeProcess, which simply starts a timer and calls processComplete after 5 seconds. Inside processComplete the calling object will be notified through its delegate that the process is done.
Adopting the Protocol
To keep the example short, I am using the applicaton delegate as the class that adopts the protocol. Here is how the app delegate looks:
#import <UIKit/UIKit.h>
#import "ClassWithProtocol.h"
 
@interface TestAppDelegate : NSObject <UIApplicationDelegate, ProcessDataDelegate>
{
  UIWindow *window;
  ClassWithProtocol *protocolTest;
}
 
@property (nonatomic, retain) UIWindow *window;
 
@end
A few things to note – ProcessDataDelegate is defined as part of the interface, which signifies that this class will adhere to the protocol. Looking back to the code for defining the protocol, notice that I added @required to the definition, which means that any class that adopts the protocol must implement the processSuccessfulmethod (you will receive a compile warning if you don’t).
Here is the implementation of the app delegate and the required method for the protocol:
#import "TestAppDelegate.h"
#import "ClassWithProtocol.h"
 
@implementation TestAppDelegate
 
@synthesize window;
 
 UITableViewDelegate
 
- (void)processSuccessful:(BOOL)success;
{
  NSLog(@"Process completed");
}
 
- (void)applicationDidFinishLaunching:(UIApplication *)application 
{   
  // Create and initialize the window
  window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
 
  protocolTest = [[ClassWithProtocol alloc] init];
  [protocolTest setDelegate:self];
  [protocolTest startSomeProcess];
 
  [window makeKeyAndVisible];
}
 
- (void)dealloc 
{
  [window release];
  [super dealloc];
}
 
@end
How it all works
Things goes as follows: the app delegate will create a new instance of theClassWithProtocol object. It sets itself as the delegate and then calls thestartSomeProcess method. At some point in the future, when the protocolTestobject has completed its work – after the 5 second timer has fired – it will call theprocessSuccessful method in the app delegate to let it know it is done processing.