Catagories: With the help of catagories you can add methods to your class without the use of inheritance and you can also add methods to those class whose source code you are not having. The syntax of defining a catagory is similar to that of a interface
@interface classname(catagory_name)
//new methods here....
@end
In my demo i will add a new method to the NSString class and use that method, so lets begin create a foundation tool based project in your Xcode
give it an appropriate name and save it i have used catagoriesDemo. Add NSObject class and give them a name i have given the name Usermethod
Before beginning just remove the inheritance part from the NSObject class
Now come to the Usermethod.h file, here we will add a new method to the NSString class which is present in the foundation framework. As you can see that the foundation header file
#import <Foundation/Foundation.h>
is already imported in our project because of this line the NSString.h is included into your project so you don't need to explicitly add the header file. So now let's do some coding
@interface NSString(Usermethod)
-(void)newMethod;
@end
In the above code you are declaring an object method called newMethod which is not present in the NSString class.
Go to the Usermethod.m file, here you will give body to this newMethod so your .m file will look somewhat like this
@implementation NSString (Usermethod)
-(void)newMethod
{
NSLog(@"This is newly added method");
}
@end
we are all set now just go to the catagoriesDemo.m file create the object of the NSString class and use this newely added function.
#import <Foundation/Foundation.h>
#import "Usermethod.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *obj = [[NSString alloc]init];
[obj newMethod];
[obj release];
[pool drain];
return 0;
}
Now when you execute this program it should give you the following output
Happy iCoding
No comments:
Post a Comment