Showing posts with label Advanced Objective-C. Show all posts
Showing posts with label Advanced Objective-C. Show all posts

Tuesday, 10 June 2014

Obj-C Memory Management

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Obj-C Memory Management

Memory management is one of the most important process in any programming language. It is the process by which the memory of objects are allocated when they are required and deallocated when they are no longer required.
Managing object memory is a matter of performance; if an application doesn't free unneeded objects, its memory footprint grows and performance suffers.
Objective-C Memory management techniques can be broadly classified into two types.
  • "Manual Retain-Release" or MRR
  • "Automatic Reference Counting" or ARC

"Manual Retain-Release" or MRR

In MRR, we explicitly manage memory by keeping track of objects on our own. This is implemented using a model, known as reference counting, that the Foundation class NSObject provides in conjunction with the runtime environment.
The only difference between MRR and ARC is that the retain and release is handled by us manually in former while its automatically taken care of in the latter.
The following figure represents an example of how memory management work in Objective-C.
Objective-C Memory management
The memory life cycle of the Class A object is shown in the above figure. As you can see, the retain count is shown below the object, when the retain count of an object becomes 0, the object is freed completely and its memory is deallocated for other objects to use.
Class A object is first created using alloc/init method available in NSObject. Now, the retain count becomes 1.
Now, class B retains the Class A's Object and the retain count of Class A's object becomes 2.
Then, Class C makes a copy of the object. Now, it is created as another instance of Class A with same values for the instance variables. Here, the retain count is 1 and not the retain count of the original object. This is represented by the dotted line in the figure.
The copied object is released by Class C using the release method and the retain count becomes 0 and hence the object is destroyed.
In case of the initial Class A Object, the retain count is 2 and it has to be released twice in order for it to be destroyed. This is done by release statements of Class A and Class B which decrements the retain count to 1 and 0, respectively. Finally, the object is destroyed.

MRR Basic Rules

  • We own any object we create: We create an object using a method whose name begins with "alloc", "new", "copy", or "mutableCopy"
  • We can take ownership of an object using retain: A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. We use retain in two situations:
    • In the implementation of an accessor method or an init method, to take ownership of an object we want to store as a property value.
    • To prevent an object from being invalidated as a side-effect of some other operation.
  • When we no longer need it, we must relinquish ownership of an object we own: We relinquish ownership of an object by sending it a release message or an autorelease message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as "releasing" an object.
  • You must not relinquish ownership of an object you do not own: This is just corollary of the previous policy rules stated explicitly.
#import <Foundation/Foundation.h>

@interface SampleClass:NSObject
- (void)sampleMethod;
@end

@implementation SampleClass

- (void)sampleMethod
{
   NSLog(@"Hello, World! \n");
}

- (void)dealloc 
{
  NSLog(@"Object deallocated");
  [super dealloc];
}

@end

int main()
{
   /* my first program in Objective-C */
   SampleClass *sampleClass = [[SampleClass alloc]init];
   [sampleClass sampleMethod];
   NSLog(@"Retain Count after initial allocation: %d", 
   [sampleClass retainCount]);
   [sampleClass retain];
   NSLog(@"Retain Count after retain: %d", [sampleClass retainCount]);
   [sampleClass release];
   NSLog(@"Retain Count after release: %d", [sampleClass retainCount]);
   [sampleClass release];
   NSLog(@"SampleClass dealloc will be called before this");
   // Should set the object to nil
   sampleClass = nil;
   return 0;
}
When we compile the above program, we will get the following output.
2013-09-28 04:39:52.310 demo[8385] Hello, World!
2013-09-28 04:39:52.311 demo[8385] Retain Count after initial allocation: 1
2013-09-28 04:39:52.311 demo[8385] Retain Count after retain: 2
2013-09-28 04:39:52.311 demo[8385] Retain Count after release: 1
2013-09-28 04:39:52.311 demo[8385] Object deallocated
2013-09-28 04:39:52.311 demo[8385] SampleClass dealloc will be called before this

"Automatic Reference Counting" or ARC

In Automatic Reference Counting or ARC, the system uses the same reference counting system as MRR, but it inserts the appropriate memory management method calls for us at compile-time. We are strongly encouraged to use ARC for new projects. If we use ARC, there is typically no need to understand the underlying implementation described in this document, although it may in some situations be helpful. For more about ARC, see Transitioning to ARC Release Notes.
As mentioned above, in ARC, we need not add release and retain methods since that will be taken care by the compiler. Actually, the underlying process of Objective-C is still the same. It uses the retain and release operations internally making it easier for the developer to code without worrying about these operations, which will reduce both the amount of code written and the possibility of memory leaks.
There was another principle called garbage collection, which is used in Mac OS-X along with MRR, but since its deprecation in OS-X Mountain Lion, it has not been discussed along with MRR. Also, iOS objects never had garbage collection feature. And with ARC, there is no use of garbage collection in OS-X too.
Here is a simple ARC example. Note this won't work on online compiler since it does not support ARC.
#import <Foundation/Foundation.h>

@interface SampleClass:NSObject
- (void)sampleMethod;
@end

@implementation SampleClass

- (void)sampleMethod
{
   NSLog(@"Hello, World! \n");
}

- (void)dealloc 
{
  NSLog(@"Object deallocated");
}

@end

int main()
{
   /* my first program in Objective-C */
   @autoreleasepool{
       SampleClass *sampleClass = [[SampleClass alloc]init];
       [sampleClass sampleMethod];
	   sampleClass = nil;
   }
   return 0;
}
When we compile the above program, we will get the following output.
2013-09-28 04:45:47.310 demo[8385] Hello, World!
2013-09-28 04:45:47.311 demo[8385] Object deallocated

Posted By MIrza Abdul Hannan11:44:00 pm

Objective-C Fast Enumeration

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Objective-C Fast Enumeration

Fast enumeration is an Objective-C's feature that helps in enumerating through a collection. So in order to know about fast enumeration, we need know about collection first which will be explained in the following section.

Collections in Objective-C

Collections are fundamental constructs. It is used to hold and manage other objects. The whole purpose of a collection is that it provides a common way to store and retrieve objects efficiently.
There are several different types of collections. While they all fulfil the same purpose of being able to hold other objects, they differ mostly in the way objects are retrieved. The most common collections used in Objective-C are:
  • NSSet
  • NSArray
  • NSDictionary
  • NSMutableSet
  • NSMutableArray
  • NSMutableDictionary
If you want to know more about these structures, please refer data storage in Foundation Framework.

Fast enumeration Syntax

for (classType variable in collectionObject )
{ 
  statements 
}
Here is an example for fast enumeration.
#import <Foundation/Foundation.h>

int main()
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   NSArray *array = [[NSArray alloc]
   initWithObjects:@"string1", @"string2",@"string3",nil];
   for(NSString *aString in array)
   {
      NSLog(@"Value: %@",aString);
   }
   [pool drain];
   return 0;
}
Now when we compile and run the program, we will get the following result.
2013-09-28 06:26:22.835 demo[7426] Value: string1
2013-09-28 06:26:22.836 demo[7426] Value: string2
2013-09-28 06:26:22.836 demo[7426] Value: string3
As you can see in the output, each of the objects in the array is printed in an order.

Fast Enumeration Backwards

for (classType variable in [collectionObject reverseObjectEnumerator] )
{ 
  statements 
}
Here is an example for reverseObjectEnumerator in fast enumeration.
#import <Foundation/Foundation.h>

int main()
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   NSArray *array = [[NSArray alloc]
   initWithObjects:@"string1", @"string2",@"string3",nil];
   for(NSString *aString in [array reverseObjectEnumerator])
   {
      NSLog(@"Value: %@",aString);
   }
   [pool drain];
   return 0;
}
Now when we compile and run the program, we will get the following result.
2013-09-28 06:27:51.025 demo[12742] Value: string3
2013-09-28 06:27:51.025 demo[12742] Value: string2
2013-09-28 06:27:51.025 demo[12742] Value: string1
As you can see in the output, each of the objects in the array is printed but in the reverse order as compared to normal fast enumeration.

Posted By MIrza Abdul Hannan11:42:00 pm

Obj-C Foundation Framework

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Obj-C Foundation Framework

If you refer Apple documentation, you can see the details of Foundation framework as given below.
The Foundation framework defines a base layer of Objective-C classes. In addition to providing a set of useful primitive object classes, it introduces several paradigms that define functionality not covered by the Objective-C language. The Foundation framework is designed with these goals in mind:
  • Provide a small set of basic utility classes.
  • Make software development easier by introducing consistent conventions for things such as deallocation.
  • Support Unicode strings, object persistence, and object distribution.
  • Provide a level of OS independence to enhance portability.
The framework was developed by NeXTStep, which was acquired by Apple and these foundation classes became part of Mac OS X and iOS.
Since it was developed by NeXTStep, it has class prefix of "NS".
We have used Foundation Framework in all our sample programs. It is almost a must to use Foundation Framework.
Generally, we use something like #import <Foundation/NSString.h> to import a Objective-C class, but in order avoid importing too many classes, it's all imported in #import <Foundation/Foundation.h>.
NSObject is the base class of all objects including the foundation kit classes. It provides the methods for memory management. It also provides basic interface to the runtime system and ability to behave as Objective-C objects. It doesn't have any base class and is the root for all classes.

Foundation Classes based on functionality

Loop TypeDescription
Data storageNSArray, NSDictionary, and NSSet provide storage for Objective-C objects of any class.
Text and stringsNSCharacterSet represents various groupings of characters that are used by the NSString and NSScanner classes. The NSString classes represent text strings and provide methods for searching, combining, and comparing strings. An NSScanner object is used to scan numbers and words from an NSString object.
Dates and timesThe NSDate, NSTimeZone, and NSCalendar classes store times and dates and represent calendrical information. They offer methods for calculating date and time differences. Together with NSLocale, they provide methods for displaying dates and times in many formats and for adjusting times and dates based on location in the world.
Exception handlingException handling is used to handle unexpected situations and it's offered in Objective-C with NSException.
File handlingFile handling is done with the help of class NSFileManager.
URL loading systemA set of classes and protocols that provide access to common Internet protocols.

Posted By MIrza Abdul Hannan11:40:00 pm

Objective-C Composite Objects

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Objective-C Composite Objects

We can create subclass within a class cluster that defines a class that embeds within it an object. These class objects are composite objects.
So you might be wondering what's a class cluster. So we will first see what's a class cluster.

Class Clusters

Class clusters are a design pattern that the Foundation framework makes extensive use of. Class clusters group a number of private concrete subclasses under a public abstract superclass. The grouping of classes in this way simplifies the publicly visible architecture of an object-oriented framework without reducing its functional richness. Class clusters are based on the Abstract Factory design pattern.
To make it simple, instead of creating multiple classes for similar functions, we create a single class that will take care of its handling based on the value of input.
For example, in NSNumber we have many clusters of classes like char, int, bool and so on. We group all of them to a single class that takes care of handling the similar operations in a single class. NSNumber actually wraps the value of these primitive types into objects.

So what's exactly composite object?

By embedding a private cluster object in an object of our own design, we create a composite object. This composite object can rely on the cluster object for its basic functionality, only intercepting messages that the composite object wants to handle in some particular way. This architecture reduces the amount of code we must write and lets you take advantage of the tested code provided by the Foundation Framework.
This is explained in the following figure.
Objective-C Composite Objects
The composite object must declare itself to be a subclass of the cluster's abstract superclass. As a subclass, it must override the superclass' primitive methods. It can also override derived methods, but this isn't necessary because the derived methods work through the primitive ones.
The count method of the NSArray class is an example; the intervening object's implementation of a method it overrides can be as simple as:
- (unsigned)count 
{
return [embeddedObject count];
}
In the above example, embedded object is actually of type NSArray.

A Composite Object example

Now in order to see a complete example, let's look at the example from the Apple documentation which is given below.
#import <Foundation/Foundation.h>

@interface ValidatingArray : NSMutableArray
{
    NSMutableArray *embeddedArray;
}

+ validatingArray;
- init;
- (unsigned)count;
- objectAtIndex:(unsigned)index;
- (void)addObject:object;
- (void)replaceObjectAtIndex:(unsigned)index withObject:object;
- (void)removeLastObject;
- (void)insertObject:object atIndex:(unsigned)index;
- (void)removeObjectAtIndex:(unsigned)index;

@end

@implementation ValidatingArray
- init
{
   self = [super init];
   if (self) {
      embeddedArray = [[NSMutableArray allocWithZone:[self zone]] init];
   }
   return self;
}

+ validatingArray
{
   return [[self alloc] init] ;
}
- (unsigned)count
{
   return [embeddedArray count];
}
- objectAtIndex:(unsigned)index
{
    return [embeddedArray objectAtIndex:index];
}
- (void)addObject:(id)object
{
   if (object != nil) {
      [embeddedArray addObject:object];
   }
}
- (void)replaceObjectAtIndex:(unsigned)index withObject:(id)object;
{
   if (index <[embeddedArray count] && object != nil) {
       [embeddedArray replaceObjectAtIndex:index withObject:object];
   }
}
- (void)removeLastObject;
{
   if ([embeddedArray count] > 0) {
       [embeddedArray removeLastObject];
   }
}
- (void)insertObject:(id)object atIndex:(unsigned)index;
{
   if (object != nil) {
       [embeddedArray insertObject:object atIndex:index];
   }
}
- (void)removeObjectAtIndex:(unsigned)index;
{
   if (index <[embeddedArray count]) {
       [embeddedArray removeObjectAtIndex:index];
   }
}

@end

int main()
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   ValidatingArray *validatingArray = [ValidatingArray validatingArray];
   [validatingArray addObject:@"Object1"];
   [validatingArray addObject:@"Object2"];
   [validatingArray addObject:[NSNull null]];
   [validatingArray removeObjectAtIndex:2];
   NSString *aString = [validatingArray objectAtIndex:1];
   NSLog(@"The value at Index 1 is %@",aString);
   [pool drain];
   return 0;
}
Now when we compile and run the program, we will get the following result.
2013-09-28 22:03:54.294 demo[6247] The value at Index 1 is Object2
In the above example, we can see that validating array's one function would not allow adding null objects that will lead to crash in the normal scenario. But our validating array takes care of it. Similarly, each of the method in validating array adds validating processes apart from the normal sequence of operations.

Posted By MIrza Abdul Hannan11:39:00 pm

Objective-C Composite Objects

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Objective-C Composite Objects

We can create subclass within a class cluster that defines a class that embeds within it an object. These class objects are composite objects.
So you might be wondering what's a class cluster. So we will first see what's a class cluster.

Class Clusters

Class clusters are a design pattern that the Foundation framework makes extensive use of. Class clusters group a number of private concrete subclasses under a public abstract superclass. The grouping of classes in this way simplifies the publicly visible architecture of an object-oriented framework without reducing its functional richness. Class clusters are based on the Abstract Factory design pattern.
To make it simple, instead of creating multiple classes for similar functions, we create a single class that will take care of its handling based on the value of input.
For example, in NSNumber we have many clusters of classes like char, int, bool and so on. We group all of them to a single class that takes care of handling the similar operations in a single class. NSNumber actually wraps the value of these primitive types into objects.

So what's exactly composite object?

By embedding a private cluster object in an object of our own design, we create a composite object. This composite object can rely on the cluster object for its basic functionality, only intercepting messages that the composite object wants to handle in some particular way. This architecture reduces the amount of code we must write and lets you take advantage of the tested code provided by the Foundation Framework.
This is explained in the following figure.
Objective-C Composite Objects
The composite object must declare itself to be a subclass of the cluster's abstract superclass. As a subclass, it must override the superclass' primitive methods. It can also override derived methods, but this isn't necessary because the derived methods work through the primitive ones.
The count method of the NSArray class is an example; the intervening object's implementation of a method it overrides can be as simple as:
- (unsigned)count 
{
return [embeddedObject count];
}
In the above example, embedded object is actually of type NSArray.

A Composite Object example

Now in order to see a complete example, let's look at the example from the Apple documentation which is given below.
#import <Foundation/Foundation.h>

@interface ValidatingArray : NSMutableArray
{
    NSMutableArray *embeddedArray;
}

+ validatingArray;
- init;
- (unsigned)count;
- objectAtIndex:(unsigned)index;
- (void)addObject:object;
- (void)replaceObjectAtIndex:(unsigned)index withObject:object;
- (void)removeLastObject;
- (void)insertObject:object atIndex:(unsigned)index;
- (void)removeObjectAtIndex:(unsigned)index;

@end

@implementation ValidatingArray
- init
{
   self = [super init];
   if (self) {
      embeddedArray = [[NSMutableArray allocWithZone:[self zone]] init];
   }
   return self;
}

+ validatingArray
{
   return [[self alloc] init] ;
}
- (unsigned)count
{
   return [embeddedArray count];
}
- objectAtIndex:(unsigned)index
{
    return [embeddedArray objectAtIndex:index];
}
- (void)addObject:(id)object
{
   if (object != nil) {
      [embeddedArray addObject:object];
   }
}
- (void)replaceObjectAtIndex:(unsigned)index withObject:(id)object;
{
   if (index <[embeddedArray count] && object != nil) {
       [embeddedArray replaceObjectAtIndex:index withObject:object];
   }
}
- (void)removeLastObject;
{
   if ([embeddedArray count] > 0) {
       [embeddedArray removeLastObject];
   }
}
- (void)insertObject:(id)object atIndex:(unsigned)index;
{
   if (object != nil) {
       [embeddedArray insertObject:object atIndex:index];
   }
}
- (void)removeObjectAtIndex:(unsigned)index;
{
   if (index <[embeddedArray count]) {
       [embeddedArray removeObjectAtIndex:index];
   }
}

@end

int main()
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   ValidatingArray *validatingArray = [ValidatingArray validatingArray];
   [validatingArray addObject:@"Object1"];
   [validatingArray addObject:@"Object2"];
   [validatingArray addObject:[NSNull null]];
   [validatingArray removeObjectAtIndex:2];
   NSString *aString = [validatingArray objectAtIndex:1];
   NSLog(@"The value at Index 1 is %@",aString);
   [pool drain];
   return 0;
}
Now when we compile and run the program, we will get the following result.
2013-09-28 22:03:54.294 demo[6247] The value at Index 1 is Object2
In the above example, we can see that validating array's one function would not allow adding null objects that will lead to crash in the normal scenario. But our validating array takes care of it. Similarly, each of the method in validating array adds validating processes apart from the normal sequence of operations.

Posted By MIrza Abdul Hannan11:38:00 pm