iDev: Used Delegation, Notification, or Observation in iOS

When to use Delegation, Notification, or Observation in iOS

 A common problem that we often experience when developing iOS applications, is how to allow communication between our controllers, without the need to have excessive coupling. Three common patterns that appear time and time again throughout iOS applications include:

  1. Delegation
  2. Notification Center, and
  3. Key value observing

So why do we need these patterns and when should and shouldn’t they be used?

The following discussion of the three patterns are purely from my own experiences of developing iOS applications. I’d like to discuss why I feel a particular pattern is better than another and why I believe certain patterns are better in certain circumstances. The reasons I give are not gospel, and are just my personal opinions. Please feel free to argue and provide me with reasons and experiences you’ve had.

What is it about these three patterns?

The three patterns chosen are all ways for one object to communicate events to other objects without requiring them to be coupled. They are ways for objects to “inform” the occurrence of certain events, or more accurately, ways to allow certain events to be heard by others. This is quite a common task for objects to have to do, as without communication, controllers cannot integrate into the application. Another goal of a controller however, is to be as self contained as possible. We want our controllers to be able to exist on their own, without coupling them to any other controllers above them in you controllers hierarchy. Controllers can create other controllers and communicate freely with them, but what we don’t want is controllers being tied back up to their creator. If we do couple them, then we lose their ability to be reused and lose their ability to completely control an isolated component of our application.

The three patterns all provide ways for controllers (or other objects) to communicate and be useful within an application, without the need to couple them and lose their self-containment. Whilst I’ll be describing the patterns and their use in iOS application, it is important to note that they do exist and are used elsewhere. The comments I make may or may not apply to their use in other contexts.


When you first start out programming iOS application, you’ll most likely notice the continued use of “delegates” throughout the SDK. The delegation pattern is not a pattern specific to iOS, but depending on what programming background you’ve had, it might not be immediately obvious as to what advantages this pattern provides, and why it seems to be used so often.

The basic idea of delegation, is that a controller defines a protocol (a set of method definitions) that describe what a delegate object must do in order to be allowed to respond to a controller’s events. The protocol is a contract where the delegator says “If you want to be my delegate, then you must implement these methods”. What this does is allows the controller to call methods on it’s delegate with the knowledge that the delegate will respond to the method calls. The delegate can be of any object type, so the controller is not coupled to a particular Object, but it can still be sure that the delegate will respond when it tries to tell it things.


  • Very strict syntax. All events to be heard are clearly defined in the delegate protocol.
  • Compile time Warnings / Errors if a method is not implemented as it should be by a delegate.
  • Protocol defined within the scope of the controller only.
  • Very traceable, and easy to identify flow of control within an application.
  • Ability to have multiple protocols defined one controller, each with different delegates.
  • No third party object required to maintain / monitor the communication process.
  • Ability to receive a returned value from a called protocol method. This means that a delegate can help provide information back to a controller.


  • Many lines of code required to define: 1. the protocol definition, 2. the delegate property in the controller, and 3. the implementation of the delegate method definitions within the delegate itself.
  • Need to be careful to correctly set delegates to nil on object deallocation, failure to do so can cause memory crashes by calling methods on deallocated objects.
  • Although possible, it can be difficult and the pattern does not really lend itself to have multiple delegates of the same protocol in a controller (telling multiple objects about the same event)


In iOS applications there is a concept of a “Notification Center”. It is a singleton object that allows for objects to be notified of events occurring. It allows us to satisfy the goal of communicating between a controller and an arbitrary object with a low level of coupling. The basic concept of this pattern is that a controller uses a key (notification name) in order to allow other objects to hear about special events occurring within the controller. Then unbeknown to the controller, other objects (observers) can react to the notification events by registering for notifications with the same key.


  • Easy to implement, with not many lines of code.
  • Can easily have multiple objects reacting to the same notification being posted.
  • Controller can pass in a context (dictionary) object with custom information (userInfo) related to the notification being posted.


  • No compile time to checks to ensure that notifications are correctly handled by observers.
  • Required to un-register with the notification center if your previously registered object is deallocated.
  • Not very traceable. Attempting to debug issues related to application flow and control can be very difficult.
  • Third party object required to manage the link between controllers and observer objects.
  • Notification Names, and UserInfo dictionary keys need to be known by both the observers and the controllers. If these are not defined in a common place, they can very easily become out of sync.
  • No ability for the controller to get any information back from an observer after a notification is posted.


Key value observing (KVO) is a pattern in which one object can observe the value of another object’s properties to find out about changes. Where the previous two patterns (delegation and notifications) are more suited to a controller communicating with arbitrary objects, KVO is more suited for objects of any type listening for changes of another arbitrary object (not necessarily, and most often not a controller). It is a way in which we can keep our objects in sync with one another; a way in which we can make one object react when another object’s state changes. It is only used for properties and cannot be used to respond to methods or other actions.


  • Can provide an easy way to sync information between two objects. For example, a model and a view.
  • Allows us to respond to state changes inside objects that we did not create, and don’t have access to alter the implementations of (SKD objects).
  • Can provide us with the new value and previous value of the property we are observing.
  • Can use key paths to observe properties, thus nested objects can be observed.
  • Complete abstraction of the object being observed, as it does not need any extra code to allow it to be observed.


  • The properties we wish to observe, must be defined using strings. Thus no compile time warnings or checking occurs.
  • Re-factoring of properties can leave our observation code no longer working.
  • Complex “IF” statements required if an object is observing multiple values. This is because all observation code is directed through a single method.
  • Need to remove the observer when it is deallocated.

Summing up the options

With these three patterns providing both pros and cons, how do we aggregate and sum these up in order influence which pattern to use in which situation. There is no right or wrong pattern to use. Each pattern provides a way for objects to inform other objects of events, without the need for the informer to know about the listener. Of these three patterns I think Key Value Observing has the clearest use case, and has a clear suitability to a specific requirement. The other two patterns however have very similar uses, and are often used to provide communication between controllers. So which of these two should be use when?

In my personal experience of making iOS applications, I have often seen an excessive use of the Notification pattern. I personally very much dislike using the notification center. I find it is just too hard to follow the flow of your application. Keys for the UserInfo dictionaries passed around become out of sync, and too many constants need to be defined and placed in a common place. It is very hard for developers who start work on an existing project to understand the flow of an application when the notification center is used excessively.

I believe that communication between controllers should be made very clear through the use of well named protocols and well named protocol method definitions. Making the effort to define these protocol methods will yield much easier code to read, and provide much more traceability within your app. Changes to delegate protocols and implementations will be picked up by the compiler, and if not (EG if you are using selectors) your app will at least crash during development, rather than just having things not working properly. Even in scenarios where multiple controllers need to be informed of the same event, as long as your application is well structured in a controller hierarchy, messages can be passed up the hierarchy where they can be passed back down to all controllers that need to know of the events.

Of course there are exceptions where the delegation pattern just does not fit and notifications make more sense. An example might be an event that every controller in your application needs to know of. However these types of scenarios are very rare. Another example might be in scenarios whereby you are building a framework that needs to announce events to the application it is running in.

As a rule of thumb I will only use observation, for property level events within objects that I did not code, or for property level events within model objects that are tightly bound to a view object. For all other events, I will always try to use a delegate pattern, if for some reason I can’t do that, I will first assess whether I have something critically wrong with my app’s structure, and if not, only then will I use notifications.

More details will be soon available by me.

Keep Coding 🙂


iDev: A Short Practical Guide to Blocks

A Short Practical Guide to Blocks

Blocks are a powerful C-language feature that is part of Cocoa application development. They are similar to “closures” and “lambdas” you may find in scripting and programming languages such as Ruby, Python, and Lisp. Although the syntax and storage details of blocks might at first glance seem cryptic, you’ll find that it’s actually quite easy to incorporate blocks into your projects’ code.

The following discussion gives a high-level survey of the features of blocks and illustrates the typical ways in which they are used. Refer to Blocks Programming Topics for the definitive description of blocks.


Why Use Blocks?

Blocks are objects that encapsulate a unit of work—or, in less abstract terms, a segment of code—that can be executed at any time. They are essentially portable and anonymous functions that one can pass in as arguments of methods and functions or that can be returned from methods and functions. Blocks themselves have a typed argument list and may have inferred or declared returned type. You may also assign a block to a variable and then call it just as you would a function.

The caret symbol (^) is used as a syntactic marker for blocks. For example, the following code declares a block variable taking two integers and returning an integer value. It provides the parameter list after the second caret and the implementing code within the braces, and assigns these to the Multiply variable:

  • int (^Multiply)(int, int) = ^(int num1, int num2) {
  •     return num1 * num2;
  • };
  • int result = Multiply(7, 4); // Result is 28.

As method or function arguments, blocks are a type of callback and could be considered a form of delegation limited to the method or function. By passing in a block, calling code can customize the behavior of a method or function. When invoked, the method or function performs some work and, at the appropriate moments, calls back to the invoking code—via the block—to request additional information or to obtain application-specific behavior from it.

An advantage of blocks as function and method parameters is that they enable the caller to provide the callback code at the point of invocation. Because this code does not have to be implemented in a separate method or function, your implementation code can be simpler and easier to understand. Take notifications of the NSNotification variety as an example. In the “traditional” approach, an object adds itself as an observer of a notification and then implements a separate method (identified by a selector in the addObserver:.. method) to handle the notification:

  • - (void)viewDidLoad {
  •    [super viewDidLoad];
  •     [[NSNotificationCenter defaultCenter] addObserver:self
  •         selector:@selector(keyboardWillShow:)
  •         name:UIKeyboardWillShowNotification object:nil];
  • }
  • - (void)keyboardWillShow:(NSNotification *)notification {
  •     // Notification-handling code goes here.
  • }

With the addObserverForName:object:queue:usingBlock: method you can consolidate the notification-handling code with the method invocation:

  • - (void)viewDidLoad {
  •     [super viewDidLoad];
  •     [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification
  •          object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notif) {
  •              // Notification-handling code goes here. 
  •     }];
  • }

An even more valuable advantage of blocks over other forms of callback is that a block shares data in the local lexical scope. If you implement a method and in that method define a block, the block has access to the local variables and parameters of the method (including stack variables) as well as to functions and global variables, including instance variables. This access is read-only by default, but if you declare a variable with the __block modifier, you can change its value within the block. Even after the method or function enclosing a block has returned and its local scope is destroyed, the local variables persist as part of the block object as long as there is a reference to the block.

Blocks in the System Framework APIs

One obvious motivation for using blocks is that an increasing number of the methods and functions of the system frameworks take blocks as parameters. One can discern a half-dozen or so use cases for blocks in framework methods:

  • Completion handlers

  • Notification handlers

  • Error handlers

  • Enumeration

  • View animation and transitions

  • Sorting

The sections that follow describe each of these cases. But before we get to that, here is a quick overview on interpreting block declarations in framework methods. Consider the following method of the NSSet class:

  • - (NSSet *)objectsPassingTest:(BOOL (^)(id obj, BOOL *stop))predicate

The block declaration indicates that the method passes into the block (for each enumerated item) a dynamically typed object and a by-reference Boolean value; the block returns a Boolean value. (What these parameters and return value are actually for are covered in “Enumeration”.) When specifying your block, begin with a caret (^) and the parenthesized argument list; follow this with the block code itself, enclosed by braces.

  • [mySet objectsPassingTest:^(id obj, BOOL *stop) {
  •     // Code goes here: Return YES if obj passes the test and NO if obj does not pass the test.
  • }];
Completion and Error Handlers

Completion handlers are callbacks that allow a client to perform some action when a framework method or function completes its task. Often the client uses a completion handler to free state or update the user interface. Several framework methods let you implement completion handlers as blocks (instead of, say, delegation methods or notification handlers).

The UIView class has several class methods for animations and view transitions that have completion-handler block parameters. (“View Animation and Transitions” gives an overview of these methods.) The example in Listing 1-1 shows an implementation of the animateWithDuration:animations:completion: method. The completion handler in this example resets the animated view back to its original location and transparency (alpha) value a few seconds after the animation concludes.

Listing 1-1A completion-handler block

  • - (IBAction)animateView:(id)sender {
  •     CGRect cacheFrame = self.imageView.frame;
  •     [UIView animateWithDuration:1.5 animations:^{
  •         CGRect newFrame = self.imageView.frame;
  •         newFrame.origin.y = newFrame.origin.y + 150.0;
  •         self.imageView.frame = newFrame;
  •         self.imageView.alpha = 0.2;
  •     }
  •                      completion:^ (BOOL finished) {
  •                          if (finished) {
  •                              // Revert image view to original.
  •                              self.imageView.frame = cacheFrame;
  •                              self.imageView.alpha = 1.0;
  •                          }
  •     }];
  • }

Some framework methods have error handlers, which are block parameters similar to completion handlers. The method invokes them (and passes in an NSError object) when it cannot complete its task because of some error condition. You typically implement an error handler to inform the user about the error.

Notification Handlers

The NSNotificationCenter method addObserverForName:object:queue:usingBlock: lets you implement the handler for a notification at the point you set up the observation. Listing 1-2illustrates how you might call this method, defining a block handler for the notification. As with notification-handler methods, an NSNotification object is passed in. The method also takes anNSOperationQueue instance, so your application can specify an execution context on which to run the block handler.

Listing 1-2Adding an object as an observer and handling a notification using a block

  • - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
  •     opQ = [[NSOperationQueue alloc] init];
  •     [[NSNotificationCenter defaultCenter] addObserverForName:@"CustomOperationCompleted"
  •              object:nil queue:opQ
  •         usingBlock:^(NSNotification *notif) {
  •         NSNumber *theNum = [notif.userInfo objectForKey:@"NumberOfItemsProcessed"];
  •         NSLog(@"Number of items processed: %i", [theNum intValue]);
  •     }];
  • }

The collection classes of the Foundation framework—NSArrayNSDictionaryNSSet, and NSIndexSet—declare methods that perform the enumeration of a particular type of collection and that specify blocks for clients to supply code to handle or test each enumerated item. In other words, the methods perform the equivalent of the fast-enumeration construct:

  • for (id item in collection) {
  •     // Code to operate on each item in turn.
  • }

There are two general forms of the enumeration methods that take blocks. The first are methods whose names begin with enumerate and do not return a value. The block for these methods performs some work on each enumerated item. The block parameter of the second type of method is preceded by passingTest; this kind of method returns an integer or an NSIndexSet object. The block for these methods performs a test on each enumerated item and returns YES if the item passes the test. The integer or index set identifies the object or objects in the original collection that passed the test.

The code in Listing 1-3 calls an NSArray method of each of these types. The block of the first method (a “passing test” method) returns YES for every string in an array that has a certain prefix. The code subsequently creates a temporary array using the index set returned from the method. The block of the second method trims away the prefix from each string in the temporary array and adds it to a new array.

Listing 1-3Processing enumerated arrays using two blocks

  • NSString *area = @"Europe";
  • NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];
  • NSMutableArray *areaArray = [NSMutableArray arrayWithCapacity:1];
  • NSIndexSet *areaIndexes = [timeZoneNames indexesOfObjectsWithOptions:NSEnumerationConcurrent
  •                                 passingTest:^(id obj, NSUInteger idx, BOOL *stop) {
  •     NSString  *tmpStr = (NSString *)obj;
  •     return [tmpStr hasPrefix:area];
  • }];
  • NSArray *tmpArray = [timeZoneNames objectsAtIndexes:areaIndexes];
  • [tmpArray enumerateObjectsWithOptions:NSEnumerationConcurrent|NSEnumerationReverse
  •                            usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  •                                [areaArray addObject:[obj substringFromIndex:[area length]+1]];
  • }];
  • NSLog(@"Cities in %@ time zone:%@", area, areaArray);

The stop parameter in each of these enumeration methods (which is not used in the example) allows the block to pass YES by reference back to the method to tell it to quit enumerating. You do this when you just want to find the first item in the collection that matches some criteria.

Even though it does not represent a collection, the NSString class also has two methods with block parameters whose names begin with enumerate:enumerateSubstringsInRange:options:usingBlock: and enumerateLinesUsingBlock:. The first method enumerates a string by a text unit of a specified granularity (line, paragraph, word, sentence, and so on); the second method enumerates it by line only. Listing 1-4 illustrates how you might use the first method.

Listing 1-4Using a block to find matching substrings in a string

  • NSString *musician = @"Beatles";
  • NSString *musicDates = [NSString stringWithContentsOfFile:
  •     @"/usr/share/calendar/"
  •     encoding:NSASCIIStringEncoding error:NULL];
  • [musicDates enumerateSubstringsInRange:NSMakeRange(0, [musicDates length]-1)
  •     options:NSStringEnumerationByLines
  •     usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
  •            NSRange found = [substring rangeOfString:musician];
  •            if (found.location != NSNotFound) {
  •                 NSLog(@"%@", substring);
  •            }
  •       }];
View Animation and Transitions

The UIView class in iOS 4.0 introduced several class methods for animation and view transitions that take blocks. The block parameters are of two kinds (not all methods take both kinds):

  • Blocks that change the view properties to be animated

  • Completion handlers

Listing 1-5 shows an invocation of animateWithDuration:animations:completion:, a method that has both kinds of block parameters. In this example, the animation makes the view disappear (by specifying zero alpha) and the completion handler removes it from its superview.

Listing 1-5Simple animation of a view using blocks

  • [UIView animateWithDuration:0.2 animations:^{
  •         view.alpha = 0.0;
  •     } completion:^(BOOL finished){
  •         [view removeFromSuperview];
  •     }];

Other UIView class methods perform transitions between two views, including flips and curls. The example invocation of transitionWithView:duration:options:animations:completion:in Listing 1-6 animates the replacement of a subview as a flip-left transition. (It does not implement a completion handler.)

Listing 1-6Implementing a flip transition between two views

  • [UIView transitionWithView:containerView duration:0.2
  •                    options:UIViewAnimationOptionTransitionFlipFromLeft
  •                 animations:^{
  •                     [fromView removeFromSuperview];
  •                     [containerView addSubview:toView]
  •                 }
  •                 completion:NULL];

The Foundation framework declares the NSComparator type for comparing two items:

  • typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);

NSComparator is a block type that takes two objects and returns an NSComparisonResult value. It is a parameter in methods of NSSortDescriptorNSArray, and NSDictionary and is used by instances of those classes for sorting. Listing 1-7 gives an example of its use.

Listing 1-7Sorting an array using an NSComparator block

  • NSArray *stringsArray = [NSArray arrayWithObjects:
  •                                  @"string 1",
  •                                  @"String 21",
  •                                  @"string 12",
  •                                  @"String 11",
  •                                  @"String 02", nil];
  • static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch |
  •         NSWidthInsensitiveSearch | NSForcedOrderingSearch;
  • NSLocale *currentLocale = [NSLocale currentLocale];
  • NSComparator finderSort = ^(id string1, id string2) {
  •     NSRange string1Range = NSMakeRange(0, [string1 length]);
  •     return [string1 compare:string2 options:comparisonOptions range:string1Range locale:currentLocale];
  • };
  • NSLog(@"finderSort: %@", [stringsArray sortedArrayUsingComparator:finderSort]);

This example is taken from Blocks Programming Topics.

Blocks and Concurrency

Blocks are portable and anonymous objects encapsulating a unit of work that can be performed asynchronously at a later time. Because of this essential fact, blocks are a central feature of both Grand Central Dispatch (GCD) and the NSOperationQueue class, the two recommended technologies for concurrent processing.

For more about GCD, NSOperationQueue, and NSOperation, see Concurrency Programming Guide.

Reference From : Apple Link

iDev: True difference between Hash Table and Dictionary

True difference between Hash Table and Dictionary



Hash Table


A dictionary is a data structure that maps keys to values.

A hash table is a data structure that maps keys to values by taking the hash value of the key (by applying some hash function to it) and mapping that to a bucket where one or more values is stored.


Dictionary is not a threadsafe.

Hashtable is threadsafe.


Dictionary is types means that the values need not to boxing.

Hashtable values need to be boxed or unboxed because it stored the values and keys as objects.        


When you try to get the value of key which does not exists in the collection, the dictionary throws an exception of ‘KeyNotFoundException’.

When you try to get the value of key which does not exists in the collection, the Hashtable returns a NULL value.


When using large collection of key value pairs dictionary is not as good as Hashtable.

When using large collection of key value pairs hashtable would be considered more efficient than dictionary.


When we retrieve the record in collection the dictionary maintains the order of entries by which entries were added.

When we retrieve the record in collection the hashtable does not maintain the order of entries.


Dictionary relies on chaining.

Hashtable relies on rehashing.


Dictionary is Abstract Base class of Hash Table.

Hash Table is Derived by Dictionary class.


Dictionary is Generic Type.

Hash Table is not generic type.


iDev: Encryption in Objective-C

Hello Friends:

In this Article/Post, I introduced the one encryption technique in Objective-C.

images (1)

Encryption Component Features in all 

  • Symmetric Encryption: AES, Blowfish, Twofish, RC2, ARC4, DES, 3DES, PBES1, PBES2.
  • Hash AlgorithmsSHA-1, SHA256, SHA384, SHA512, MD2, MD4, MD5, HAVAL.
  • Hash Algorithms: RIPEMD128, RIPEMD160, RIPEMD256, RIPEMD320.
  • Encoding: Base64, hex, quoted-printable, URL-encoding.
  • HMAC with any supported hash algorithm: HMAC-MD5, HMAC-SHA1, etc.
  • Password-based Key Derivation Functions: PBKDF1, PBKDF2
  • PKCS7 — P7S and P7M creation, decryption, verification.
  • Public key encryption/decryption with digital certificates.
  • Digital signature creation/verification with digital certificates.
  • Bzip2 in-memory compression.
  • Encrypt / decrypt strings or byte data.
  • Return encrypted data as Base64, quoted-printable, or hex-encoded strings.
  • Hash strings or binary data using SHA1, MD2, MD5, HAVAL, SHA384, or SHA512.
  • Public-key encryption with digital certificates.
  • Create and verify digital signatures.
  • Pre-convert Unicode strings to ANSI (single-byte/char) before encrypting.
  • Pre-convert Unicode strings to any charset before encrypting, compressing, or hashing.
  • Base64 encode strings or byte data.
  • Hex-encode encode strings or byte data.
  • Compress strings or byte data with the BZIP2 compression algorithm.
  • Implements FIPS81 padding scheme for AES.
  • Up to 256-bit encryption is supported.
  • Set binary secret-key directly for symmetric encryption algorithms.
  • Initialization vectors.
  • CBC (Cipher Block Chaining) Mode
  • ECB (Electronic Cookbook) Mode
  • Random byte data generation.
  • Streaming hashing (pass data to hashing functions in chunks).
  • Streaming encryption (pass data to encryption functions in chunks).


imagesHMAC is not an encryption mechanism, but an authentication digest. It uses an underlying message digest function such as SHA-1, SHA-256, MD5 etc, with a secret key to generate a code that can be used to authenticate data.

Generating an HMAC digest is extremely simple. Here is the description from RFC2104 (via Wikipedia)


  • H(·) be a cryptographic hash function (ie. SHA-1, SHA-256, MD5 etc)
  • K be a secret key padded to the right with extra zeros to the input block size of the hash function, or the hash of the original key if it’s longer than that block size
  • m be the message to be authenticated
  • | denote concatenation
  • ⊕ denote exclusive or (XOR)
  • opad be the outer padding (0x5c5c5c…5c5c, one-block-long hexadecimal constant)
  • ipad be the inner padding (0x363636…3636, one-block-long hexadecimal constant)

Then HMAC(K,m) is mathematically defined by:

HMAC(K,m) = H((K ⊕ opad) | H((K ⊕ ipad) | m)).

For the underlying digest function you can help yourself to one of the C implementations from OpenSSL. In fact it also has a C implementation of HMAC_MD5 that you can probably just use like this.

Example :

Sometimes it is necessary to implement some cryptographic functions for security reasons within your iOS apps. In one of our projects I was faced with the problem of implementing some kind of a two-step registration/confirmation process with a iOS app and a corresponding server-side interface. We decided to implement this by using a generated confirmation code based on HMAC and MD5. Since there is no native support of the iOS framework to realize this, I needed to implement it on my own.

Due to this post Implementing HMAC encryption algorithm in iPhone application it was quite easy to implement a simple category for NSString to provide this functionality. The following code creates a HMAC+MD5 encrypted string based on a given secret and returns it in a hexadecimal string representation.

Code :

@implementation NSString (HMAC_MD5)

– (NSString*) HMAC_MD5_WithSecretString:(NSString*)secret{

    CCHmacContext    ctx;

    const char       *key = [secret UTF8String];

    const char       *str = [self UTF8String];

    unsigned char    mac[CC_MD5_DIGEST_LENGTH];

    char             hexmac[2 * CC_MD5_DIGEST_LENGTH + 1];

    char             *p;

    CCHmacInit( &ctx, kCCHmacAlgMD5, key, strlen( key ));

    CCHmacUpdate( &ctx, str, strlen(str) );

    CCHmacFinal( &ctx, mac );

    p = hexmac;

    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++ ) {

        snprintf( p, 3, “%02x”, mac[ i ] );

        p += 2;


    return [NSString stringWithUTF8String:hexmac];



Calling Technique:


NSString *stringToEncrypt  = @”encryptedTextByNiketanMishra”;

NSString *secret           = @”SECRET_KEY”;

NSString *hexHmac          = [stringToEncrypt HMAC_MD5_WithSecretString:secret];

NSLog(@”HMAC_MD5 in hex is %@”, hexHmac);

Output : HMAC_MD5 in hex is 193e7a3ee3ec7bcc70bf3ddbcdd63fdf

Download Here

Other Information:


Use the Common Crypto functions (See Apple Links). They’re in libSystem on iOS and Mac OS X, so no need to add another library or framework to your project. As you can see from the example below, the API is very similar to


Here the original Code :

#include <CommonCrypto/CommonHMAC.h>

#include <sys/types.h>

#include <errno.h>

#include <fcntl.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

extern int      errno;


main( int ac, char *av[] )


    CCHmacContext    ctx;

    char             *key = “secret”;

    char             buf[ 8192 ];

    unsigned char    mac[ CC_MD5_DIGEST_LENGTH ];

    char             hexmac[ 2 * CC_MD5_DIGEST_LENGTH + 1 ];

    char             *p;

    int              fd;

    int              rr, i;

    if ( ac != 2 ) {

        fprintf( stderr, “usage: %s path\n”, av[ 0 ] );

        exit( 1 );


    if (( fd = open( av[ 1 ], O_RDONLY )) < 0 ) {

        fprintf( stderr, “open %s: %s\n”, av[ 1 ], strerror( errno ));

        exit( 2 );


download (1)

Let me know if you have any problem and queries regarding this post.

Thanks ..


Happy Coding 🙂

iDev: Guidelines for iOS Developer

images (2)

Here the some concern, which is always in your mind as a developer:

Apple’s iPhone – Memory Constraints

The most visible aspect for any mobile application, other than its look and feel, is the speed in terms of user interface’s responsiveness. This performance may be impacted not only by hardware constraints like processing power or available memory but also due to network delays while pulling data. Apple’s iPhone provides 128MB of RAM (iOS5 have a quad-core chip with 1 GB of RAM ), part of which is dedicated for user interface only. Even though only one user application is running at a time, still there are a bunch of applications (like mail, clock, push, music) that are running in the background consuming additional memory. Your application must be able to run under the presumption of low memory and the fact that an incoming phone call or text message will further decrease the available memory, potentially resulting in a memory warning to your application. The application will get terminated if you don’t release memory when you get these memory warnings. Ideally, your application should stay within 7-8Mb limit to successfully overcome any memory issues. Apple’s development environment comes with tools that let you gauge the memory footprint as you move through your application.

Memory Management – Objective-C

Memory management is core to any programming language, and it is always easier when you need not worry about it, like in Java or SmallTalk. But the ability to manage your own memory is a powerful aspect of Objective-C programming. When used correctly, Objective-C’s memory management using the retain/releases commands runs smoother and faster than Java’s garbage collection although it does place a much larger burden on the developer and introduces a much larger risk of memory leaks. As long as you strictly follow the simple rule, ‘You must take responsibility for releasing (i.e. de-allocating) any object that you have allocated or retained’, memory handling should be fine in Objective-C. Some background in handling memory elsewhere (like using malloc/free in C) can help expedite your learning but be aware of some interesting Objective-C specific syntax and concepts (read here).

How it works

Objective-C uses a retain/release mechanism, along with autorelease pools which provide a degree of automated memory management. It is much more elegant than C’s malloc/free (or C++’s new/delete), and provides much better control over memory management as compared to Java’s automated garbage collection. Unlike Java, where you are free to create as many objects, simply drop references when done and garbage collection will eventually notice the need to cleanup, Objective-C is stricter about managing memory. When an object is created, it has a retain count of 1. When an object is retained, the retain count is incremented and similarly when it is released the retain count is decremented. When the retain count goes to zero, the object will call [self dealloc], thereby releasing the object’s memory. This provides the developer with much more control over when the object’s physical memory is actually released.

The default convention about using the ‘retain’ and ‘release’ is that any block of code that causes an object to be allocated, ‘owns’ this object and is responsible for releasing it. More generally, the total number of ‘retain’ in a block should be matched by an equal number of ‘release’.

Cocoa library (collection of frameworks, APIs and Runtime) defines a NSObjectclass, which is the root of most Objective-C class hierarchies. NSObject implements a semi-automated reference counting version of garbage collection and other objects inherit a basic interface to the runtime system through NSObject. This interface provides procedures (listed below) for managing an object’s Retain Count and understanding the way they work are crucial to making sure your application uses proper memory management.

NSObject provides the following messages to manage objects:

  1. 1.     alloc: Creates new object by allocating physical memory and setting the reference count to 1. When done with this object, there must be a corresponding release.
  2. 2.     init: Simply initializes the object. It may be used along with ‘alloc’ and does not impact the reference count by itself. If you override init, it must always return itself (id).
  3. 3.     dealloc: Frees the memory obtained by alloc. Instead of calling dealloc directly on an object, call release – let the memory manager perform dealloc, when appropriate (i.e. if retain count becomes zero).
  4. 4.     retain: Signals that we are interested in this object causing the retain count to be incremented by one.
  5. release: Signals that we are no longer interested in this object causing the retain count to be decremented by one.

Note that if you decide to override any of these methods, be sure to call super’s corresponding method at the appropriate time.

Autorelease Pools

Autorelease pools (supported by NSAutoReleasePool class) are an important aspect of Cocoa’s memory management system that helps in lowering the overhead of dealing with retain/release semantic. An autorelease pool acts like a simple list containing objects that are to be released when the pool itself is deallocated. The AppKit (set of classes primarily dealing with user interface elements for developing applications) usually ensures that you always have an autorelease pool. You may create your own autorelease pools (they are stackable) specially when your application creates a lot of temporary autoreleased objects within a event loop in order to minimize the peak memory footprint as shown in the example below,

-(void) someFunctionDeclaration {

for(int i=0; i<100; i++) {

// create your oqn autorelease pool

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

// these objects get added to the autorelease pool you created above

NSNumber *aNumber = [NSNumber numberWithFloat:1];

NSString *aString = [NSNumber stringWithFormat:@”Temporary String Data”];

NSNumber *anotherNumber = [NSNumber numberWithFormat:N];

// … do some processing with objects created above.

[pool release]; // all objects added to this pool are released



When you send an ‘autorelease’ message to an object, that object will be added to the most recently created (on the current thread) pool’s list of items to release. Once that pool is itself released (or drained), it will send a ‘release’ message to all objects that were added to that autorelease pool, decrementing their retain count and the object may be deallocated if the retain count becomes zero. Thus, sending autorelease instead of release to an object extends the lifetime of that object at least until the pool itself is drained (it may be longer if the object is subsequently retained).

Autorelease pools are specifically useful when you don’t know how long you need an object reference, for instance when you return an object. In such scenario, you can’t send a release message to the object within the method that created it, but not releasing that object will lead to a memory leak. By sending the object an ‘autorelease’ message, it gets added to the local autorelease pool and may be further retained by the calling function, if needed. In general, all objects returned from functions (other than alloc/copy) should be considered to be autoreleased.

Handling Memory Warnings

Given low available working memory amid background applications and unpredictable user behavior, it is ofter better to sacrifice the snappy user interface for a low memory footprint and avoid any application crashes. It is recommended to delay loading all resources until they are needed. If one NIB contains a lot of views, it is better to create multiple NIBs files so as to load the NIB individually when needed.

Before an out-of-memory crash, a ‘didReceiveMemoryWarning’ message is sent to your view controllers. The purpose of ‘didReceiveMemoryWarning’ is to give you a chance to free memory or pop views to avoid a crash. It is highly recommended that you override this message in all your view controllers and handle the warning properly and free up memory, then you can avoid an application crash. Also, when ‘didReceiveMemoryWarning’ message is called, the setView message will also be called with a nil parameter. It will be called to release the view if the view is not the active view. This is where you will want to release as much resources as you can, such as all your IBOutlet variables. Also, do not forget to call the corresponding parent methods or your application will crash.

Static Code Analyzer

In addition to code reviews and careful coding practices, a static code analyzer can save many a headaches and help in discovering potential vulnerabilities. We used‘clang’ for our project that helped identifying some not so serious and also a few potentially serious bugs based on the memory footprint. We found this tool to be easy to setup with configurations that allow it to be run locally on developer’s machine or along with the build to generate reports with filenames and line numbers for easy discovery and correction.

Apple’s IDE – XCode

Apple’s IDE tool XCode is tightly integrated with Cocoa framework and includes powerful optimization and analysis tools called Instruments. Instruments collects data such as disk, memory, or CPU usage in real time on your connected iPhone that can help you track down performance bottlenecks in your applications. You can dynamically view the leaks as well as memory object allocation along with exact location in your code.

General Tips

– NSObject provides a method called retainCount that you may use to get an object’s current retain count. This can be very handy for debugging purposes as, NSLog([NSString stringWithFormat:@”Retain Count:%i”, [yourObject retainCount]]);

– You should override the ‘dealloc’ method in your classes to release any memory that you may have allocated (make sure to super’s dealloc)

– In setters methods, always retain the new object first, and then release the old object. This will take care of scenarios when same value is being set.

– When you add an object to a collection such as an array, dictionary, or set, the collection takes ownership of it. The collection will relinquish ownership when the object is removed from the collection or when the collection is itself released.

– When your view is freed while handling ‘didReceiveMemoryWarning’, the NIB will be read back into memory when it is needed the next time. This will cause ‘viewDidLoad’ message to be called again. So make sure you have the appropriate initialization code in that message.

– XCode’s Instruments allows you to manually trigger a memory warning that can be very helpful in flushing out memory warning issues.

– If you are making Cocoa calls outside of the Application Kit’s main thread—for example if you create a Foundation-only application or if you detach a thread—you need to create your own autorelease pool.

– You should always drain an autorelease pool in the same context (invocation of a method or function, or body of a loop) that it was created.

Here some tips:

For Naming convention Standard please read this link :

  1. CodingGuidelines
  2. NamingConventions


For UI Design Specification Standard

  1. Human Interface Guidelines

Every time, when you finished some task you must check  this:

  1. Warnings (Remove all Warning in the code).
  2. Analyze tools used (Xcode 4.5 & above) → remove all potential leaks , read this for run Analyze in your project :
  3. How to analyze

After completing these two steps you must check run time leaks and optimization the code, way are:

Run the Instruments on the Simulator first and test , and check the allocation and leaks, then optimized the code and remove the leaks.

For the memory management you can referred the following link:

Memory Management Tips

Managing Memory Help

How to design and memory analyse

For the Instrument Run technique you can referred the following link :

Xcode- Instrument Guide,

Finding Leaks

How to debug and finding memory leaks

For ARC enabled Architecture : Handled Memory Management referred following link :

images (1)