在c++中我们可以多继承来实现代码复用和封装使程序更加简练。在objective-c中只能单继承,不能多继承,那么除了协议protocol之外,我们可以实现类似多继承的一个方法就是,分类(category,又称类别)。类别可以不修改原来的类(父类),和派生类的情况下,为原有的类增加新的方法,但是分类不能增加实例变量。
格式(format):
@interface class_name(category_name)<protocol,....>
method _declaration;
....
@end
@implementation class_name(category_name)
method_implementation;
...
@end
新建一个AddressCard类,然后再新建一个文件 AddressCardCategory 用来声明和实现分类(category)
1 #import <Foundation/Foundation.h> 2 3 @interface AddressCard : NSObject<NSCoding>{ 4 NSString* name; 5 NSString* email; 6 } 7 @property (nonatomic,retain)NSString* name; 8 @property (nonatomic,retain)NSString* email; 9 -(id)initWithName:(NSString*)_name andEmail:(NSString*)_email; 10 11 @end
1 #import "AddressCard.h" 2 3 @implementation AddressCard 4 @synthesize name,email; 5 -(id)initWithName:(NSString*)_name andEmail:(NSString*)_email{ 6 if(self= [super init]) 7 { 8 self.name=_name; 9 self.email=_email; 10 } 11 return self; 12 } 13 -(void)encodeWithCoder:(NSCoder *)aCoder{ 14 [aCoder encodeObject:name forKey:@"_name"]; 15 [aCoder encodeObject:email forKey:@"_email"]; 16 } 17 18 -(id)initWithCoder:(NSCoder*)aDecoder{ 19 if(self=[super init]) 20 { 21 self.name=[aDecoder decodeObjectForKey:@"_name"]; 22 self.email=[aDecoder decodeObjectForKey:@"_email"]; 23 } 24 return self; 25 } 26 -(void)dealloc{ 27 [name release]; 28 [email release]; 29 [super dealloc]; 30 } 31 @end
#import <Foundation/Foundation.h> #import "AddressCard.h" @interface AddressCard(category) -(void)uppercaseName; @end
1 #import "AddressCardCategory.h" 2 3 @implementation AddressCard(Category) 4 -(void)uppercaseName{ 5 self.name= [name uppercaseString]; 6 } 7 8 @end
1 #import <Foundation/Foundation.h> 2 #import "AddressCardCategory.h" 3 int main (int argc, const char * argv[]) 4 { 5 6 @autoreleasepool { 7 AddressCard* card1=[[AddressCard alloc]initWithName:@"shou" andEmail:@"abc@126.com"]; 8 [NSKeyedArchiver archiveRootObject:card1 toFile:@"/tmp/AddressCard.txt"]; 9 AddressCard* card4=[NSKeyedUnarchiver unarchiveObjectWithFile:@"/tmp/AddressCard.txt"]; 10 NSLog(@"card 4 %@ ,%@",card4.name,card4.email); 11 [card4 uppercaseName]; 12 NSLog(@"card 4 %@ ,%@",card4.name,card4.email); 13 [card1 release]; 14 //[card4 release]; 15 16 17 } 18 return 0; 19 }
执行结果:
2013-08-20 17:12:04.751 AddressCard[1079:707] card 4 shou ,abc@126.com
2013-08-20 17:12:04.758 AddressCard[1079:707] card 4 SHOU ,abc@126.com