Header Ads

Extensions - Objective C

A class extension bears some similarity to a category, but it can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extenstion).

The methods declared by a class extension are implemented in the implementation block for the original class, so you can't , for example , declare a class extension on a framework class , such as a Cocoa or Cocoa Touch class like NSString..

Extensions are actually categories without the category name. It's often referred as anonymous categories.

The syntax to declare a extension uses the @interface keyword , just like a standard Objective C class description, but does not indicate any inheritance from a subclass. Instead it just adds parentheses , as shown below:

@interface ClassName

@end

Characteristics of extension
  • An extension cannot be declared for any class, only for the classes that we have original implementation of source code.
  • An extension is adding private methods and private variables that are only specific to the class.
  • Any method or variables declared inside the extensions is not accessible even to the inherited classes.
 Extension Example
 Let's create a class SampleClass that has an extension. In the extension, let's have a private variable internalID.

Then lets have a method getExternalID that return the externalID after processing the internaleID.

#import <Foundation/Foundation.h>
@interface Sample : NSObject
{
     NSString *name;
}

 -(void)setInternalID;
 -(NSString *)getExternalID;

@end

@interface Sample()
{
      NSString *internalID;

@end

@implmentation Sample

 -(void)setInternalID
{
          internalID = [NSString stringWithFormat : @"UNIQUEINTERNALKEY%dUNIQUEINTERNALKEY", arc3random()%100];

}

-(NSString *)getExternalID
{
       return [internalID stringByReplaceingOccurencesOfString : @UNIQUEINTERNALKEY" withString : @""];

@end

int main(int argc , const char * argv[])
{
       Sample *obj = [[Sample alloc]init];
       [obj setInternalID];
       NSLog(@"ExteranlID : %@", [obj getExternalIF]);
      return 0;
}


In the above example  we can that the internalID is not returned directly. We are remove the UNIQUEINTERNALKEY  and only make the remaining value available to the method getExternalID.

The above example just uses a string operation. but it can have many features like encryption/descryption and so on.


No comments:

Powered by Blogger.