<NSCopying,NSMutableCopying>协议
不是所有的对象都支持copy和mutableCopy,一般自定义的类需要继承NSCopying和NSMutableCopying协议,并对协议中的方法进行实现才满足使用条件。需注意NSObject没有实现这两个协议,但是copy和mutableCopy这两个方法是NSObject定义的. 加上一句(记得不大清楚了,可以去验证一下),NSString对象若使用mutableCopy,接收到的对象就变成了NSMutableString类型;若继续对这个接收的对象使用一次copy,又会接收到NSString类型。
下面以一个学生类来说明:
-----------------interface部分-----------------
@interface DMStudent :NSObject<NSCopying,NSMutableCopying>
......
-----------------implementation部分-----------------
#import "DMStudent.h"
@implementation DMStudent
@synthesize dName;
@synthesize dAge; //assign
@synthesize dSex;
@synthesize dNumber; //assign
@synthesize dGrade;
@synthesize dInterest;
@synthesize dTeacher;
@synthesize dPhone; //assign
-(void)dealloc{
[dName release];
[dSex release];
[dGrade release];
[dInterest release];
[dTeacher release];
[super dealloc];
}
//设置多条信息
-(void)setStuInfo:(NSString *)theName andAge:(int)theAgeandSex:(NSString *)theSex andNumber:(int)theNumberandGrade:(NSString *)theGrade andInterest:(NSString *)theInterestandTeacher:(NSString *)theTeacher andPhone:(int)thePhone{
[self setDName:theName];
[self setDAge:theAge];
[self setDSex:theSex];
[self setDNumber:theNumber];
[self setDGrade:theGrade];
[self setDInterest:theInterest];
[self setDTeacher:theTeacher];
[self setDPhone:thePhone];
}
//输出学生信息
-(void)printfInfo{
NSLog(@"\n----------------");
NSLog(@"\n姓名:%@",dName);
NSLog(@"\n年龄:%d",dAge);
NSLog(@"\n性别:%@",dSex);
NSLog(@"\n学号:%d",dNumber);
NSLog(@"\n班级:%@",dGrade);
NSLog(@"\n爱好:%@",dInterest);
NSLog(@"\n老师:%@",dTeacher);
NSLog(@"\n电话:%d",dPhone);
}
//NSCopying协议,方法实现
-(id)copyWithZone:(NSZone *)zone{
//先创建一个相同大小的空间;再对该对象以同样的参数初始化,
DMStudent *stuCopy = [DMStudent allocWithZone:zone];
//谁调用方法拷贝,self就表示谁
[stuCopy setStuInfo:self.dName andAge:self.dAge andSex:self.dSex andNumber:self.dNumber andRemove:self.dGrade andInterest:self.dInterest andTeacher:self.dTeacher andPoneNumber:self.dPhone];
return stuCopy;
}
//NSMutableCopying协议,方法实现
- (id)mutableCopyWithZone:(NSZone *)zone{
return [self copyWithZone:zone];
}
-----------------program部分-----------------
@autoreleasepool {
DMStudent *stuOne = [[DMStudent alloc] init] ;
[stuOne setStuInfo:@"海龟" andAge:1000 andSex:@"公"andNumber:201314520 andGrade:@"海里蹲"andInterest:@"旅游 " andTeacher:@"不详 " andPhone:110];
DMStudent*stuTwo =[stuOne copy];
//这里是深拷贝,拷贝后即便修改之前的信息,对拷贝后的数据没影响;
[stuOne setDName:@"小明"];
[stuTwo printfInfo];
DMStudent *stuThree=[stuOne mutableCopy];
[stuThree printfInfo];
}
return0;
}
转载:http://blog.csdn.net/wsyx768/article/details/17452637