Objective-C copy,看我就够了

转自: https://www.jianshu.com/p/ebbac2fec4c6?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source=toutiao.io

略作补充,通过基类实现copyWithZone和mutableCopyWithZone,来减轻手动繁琐的去实现对应的赋值或者copy等操作
代码如下:

#import "WXObject.h"
#import 

@implementation WXObject
- (id)copyWithZone:(NSZone *)zone {
    return [self wx_copyWithZone:zone];
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return [self wx_copyWithZone:zone];
}

- (id)wx_copyWithZone:(NSZone *)zone {
    id obj = [[self class] allocWithZone:zone];
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i++) {
        Ivar ivar = *(ivars + i);
        
        // 获取成员类型
        const char *type = ivar_getTypeEncoding(ivar);
        NSString *var_type = [NSString stringWithUTF8String:type];
        var_type = [var_type stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        var_type = [var_type stringByReplacingOccurrencesOfString:@"@" withString:@""];
        
        // 获取成员属性名
        const char *varName = ivar_getName(ivar);
        NSString *var_keypath = [NSString stringWithUTF8String:varName];
        var_keypath = [var_keypath stringByReplacingOccurrencesOfString:@"_" withString:@""];
        //NSLog(@"var_type = %@ var_keypath = %@",var_type,var_keypath);
        
        Class ivarClass = NSClassFromString(var_type);
        if ([ivarClass isKindOfClass:[NSObject class]]) {
            id temp = [self valueForKeyPath:var_keypath];
            if ([temp conformsToProtocol:@protocol(NSCopying)]) {
                [obj setValue:[temp copy] forKeyPath:var_keypath];
            }else if([temp conformsToProtocol:@protocol(NSMutableCopying)]){
                [obj setValue:[temp mutableCopy] forKeyPath:var_keypath];
            }
        }else {
            if (var_keypath) {
                [obj setValue:[self valueForKeyPath:var_keypath] forKeyPath:var_keypath];
            }
        }
    }
    free(ivars);
    return obj;
}
@end
集合深拷贝分类示例
#import "NSArray+Extension.h"
@implementation NSArray (Extension)
+ (instancetype)deepCopyFromArray:(NSArray *)array {
    NSMutableArray *temp = [NSMutableArray array];
    for (id obj in array) {
        [temp addObject:[obj copy]];
    }
    return [NSArray arrayWithArray:temp];
}
@end

你可能感兴趣的:(Objective-C copy,看我就够了)