Objective C中的浅拷贝和深拷贝

其实和Java很类似的,浅拷贝要实现用NSCopying,深拷贝要实现NSMutableCopying,举个例子:

摘抄自:http://stackoverflow.com/questions/11329754/is-this-a-reasonable-pattern-for-implementing-nsmutablecopying

// BBMovie.h

@interface BBMovie : NSObject < NSCopying, NSMutableCopying >
@property(readonly, nonatomic, copy) NSString *title;
@end

@interface BBMutableMovie : BBMovie
@property(readwrite, nonatomic, copy) NSString *title;
@end
// BBMovie.m (note: compiling with ARC)

@interface BBMovie ()
@property(readwrite, nonatomic, copy) NSString *title;
@end

@implementation BBMovie
@synthesize title = _title;

- (id)copyWithZone:(NSZone *)zone
{
    BBMovie *copy = [[BBMovie allocWithZone:zone] init];
    if (copy) copy.title = self.title;
    return copy;
}

- (id)mutableCopyWithZone:(NSZone *)zone
{
    BBMutableMovie *copy = [[BBMutableMovie allocWithZone:zone] init];
    if (copy) copy.title = self.title;
    return copy;
}

@end

使用的时候:

[obj copy];
[obj mutableCopy];

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *