objective-c复制

copy和 mutableCopy方法

       copy方法总是返回对象的不可修改的副本,即使对象本身是可以修改的。 例如: 调用NSMutableString的copy方法,将会得到不可修改的字符串对象。


       mutableCopy方法总是返回该对象的可以修改的副本,即使被复制的对象本身是不可修改的。 例如: 调用NSString的mutableCopy方法,将会得到NSMutableString。


       copy和mutableCopy返回的总是原对象的副本,当程序对复制的副本就行修改时原对象通常不会受影响。


像使用copy方法要先在接口声明是实现NSCopying协议,然后在类实现中重写-(id)copyWithZone:(NSZone *)zone方法。

想使用mutableCopy方法要实现NSMutableCopying协议,然后在类中实现mutanleCopyWithZone方法。


例如:

@interface  Copyyy : NSObject<NSCopying>
@property NSString* name;

@end

@implementation Copyyy


-(id)copyWithZone:(NSZone *)zone{
    NSLog(@"复制ing");

    return self;
}

@end
@implementation ttt


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        Copyyy* ccc=[Copyyy new];
        ccc.name=@"xl";
        
        Copyyy*ccc2=[ccc copy];
        
        NSLog(@"%@",ccc2.name);
    
    }
    
}

@end

当然也可以不实现NSCopying协议,直接在实现中重写
-(id)copyWithZone:(NSZone *)zone
也可以

例如

#import "ttt.h"
#import <Foundation/Foundation.h>


@interface  Copyyy : NSObject   // <NSCopying>
@property NSString* name;

@end

@implementation Copyyy


-(id)copyWithZone:(NSZone *)zone{
    NSLog(@"复制ing");

    return self;
}


@end
@implementation ttt


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        Copyyy* ccc=[Copyyy new];
        ccc.name=@"xl";
        
        Copyyy*ccc2=[ccc copy];
        
        NSLog(@"%@",ccc2.name);
    
    }
    
}

@end

甚至不实现协议,不重写
-(id)copyWithZone:(NSZone *)zone
也可以


例如

#import "ttt.h"
#import <Foundation/Foundation.h>


@interface  Copyyy : NSObject   // <NSCopying>
@property NSString* name;

@end

@implementation Copyyy

//参数任意
-(id)copyWithZone:(NSObject *)zone{
    NSLog(@"复制ing");

    return self;
}
//-(id)copyWithZone:(NSData *)zone{
//    NSLog(@"复制ing");
//    return self;
//}


@end
@implementation ttt


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        Copyyy* ccc=[Copyyy new];
        ccc.name=@"xl";
        
        Copyyy*ccc2=[ccc copy];
        
        NSLog(@"%@",ccc2.name);
    
    }
    
}

@end


你可能感兴趣的:(Objective-C)