黑马程序员-Object C之copy和mutableCopy语法(二)

来源:互联网 发布:js 上传与下载文件 编辑:程序博客网 时间:2024/06/06 03:03

------------------------------ASP.Net+Unity开发、.Net培训、期待与您交流!---------------------------


自定义对象的拷贝

首先,要知道在Object C中,并不是所有的对象都支持copymutableCopy。只有遵守NSCopying协议的类可以发送copy方法,遵守NSMutableCopying协议的类才可以发送mutableCopy方法。要实现自己定义对象的拷贝,需要遵守NSCopying或者NSMutableCopying协议,并且要实现copyWithZone:或mutableCopyWithZone:方法。

下面代码展示自定义对象的拷贝:

1.定义两个类

(1)Student类的声明:

@interface Student : NSObject <NSCopying>// copy代表set方法会release旧对象、copy新对象// 修改外面的变量,并不会影响到内部的成员变量// 建议:NSString一般用copy策略,其他对象一般用retain@property (nonatomic, copy) NSString *name;+ (id)studentWithName:(NSString *)name;@end
Student类的实现:
#import "Student.h"@implementation Student+ (id)studentWithName:(NSString *)name {    // 这里最好写[self class],当子类初始化名字时返回子类对象    Student *stu = [[[[self class] alloc] init] autorelease];    stu.name = name;//初始化姓名    return stu;}- (void)dealloc {    [_name release];    [super dealloc];}#pragma mark description方法内部不能打印self,不然会造成死循环- (NSString *)description {    return [NSString stringWithFormat:@"[name=%@]", _name];}#pragma mark copying协议的方法// 这里创建的副本对象不要求释放- (id)copyWithZone:(NSZone *)zone {    Student *copy = [[[self class] allocWithZone:zone] init];        // 拷贝名字给副本对象    copy.name = self.name;        return copy;}@end
(2)GoodStudent类,为Student的子类
@interface GoodStudent : Student@property (nonatomic, assign) int age;+ (id)goodStudentWithAge:(int)age name:(NSString *)name;@end
GoodStudent类的实现:
#import "GoodStudent.h"@implementation GoodStudent+ (id)goodStudentWithAge:(int)age name:(NSString *)name {    GoodStudent *good = [GoodStudent studentWithName:name];    good.age = age;//初始化年您    return good;}- (NSString *)description {    return [NSString stringWithFormat:@"[name=%@, age=%i]", self.name, _age];}- (id)copyWithZone:(NSZone *)zone {    // 一定要调用父类的方法    GoodStudent *copy = [super copyWithZone:zone];     copy.age = self.age; //拷贝年您给副本对象    return copy;}@end
测试代码:

#pragma mark 演示Student的name的copyvoid studentNameCopy() {    Student *stu = [[[Student alloc] init] autorelease];    NSMutableString *string = [NSMutableString stringWithFormat:@"age is %i", 10];    stu.name = string;        [string appendString:@"abcd"];    //不会影响name的改变    NSLog(@"name=%@", stu.name);    NSLog(@"string=%@", string);}#pragma mark 演示Student的copyvoid studentCopy() {    Student *stu1 = [Student studentWithName:@"stu1"];    Student *stu2 = [stu1 copy];//对象的copy    stu2.name = @"stu2";        NSLog(@"stu1:%@", stu1);    NSLog(@"stu2:%@", stu2);        [stu2 release];}void goodStudentCopy() {    GoodStudent *stu1 = [GoodStudent goodStudentWithAge:10 name:@"good1"];    GoodStudent *stu2 = [stu1 copy];    stu2.name = @"good2";    stu2.age = 11;        NSLog(@"stu1:%@", stu1);    NSLog(@"stu2:%@", stu2);}

-----------------------------ASP.Net+Unity开发、.Net培训、期待与您交流!-------------------------

详细请查看:www.itheima.com

0 0
原创粉丝点击