Objective-C copy, 나만 보면 돼.

2466 단어
다음으로 이동: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

좋은 웹페이지 즐겨찾기