runtime 实现 NSCopying copyWithZong

 

有时候项目中会有些model须要copy, 这个时候就须要实现 NSCopying 协议方法copyWithZone了3d

可是不少时候都是一个个属性来赋值, 这样作属性少还能够, 可是若是有不少属性呢, 难道也要一个一个去赋值吗? 显然还须要更好的解决办法对象

如下是用runtime来实现copyWithZong方法的姿式:blog

 

 

// copy代码请下拉:get

- (id)copyWithZone:(NSZone *)zone {string

    id objCopy = [[[self class] allocWithZone:zone] init];it

    // 1.获取属性列表class

    unsigned int propertyCount = 0;List

    objc_property_t * propertyArray = class_copyPropertyList([self class], &propertyCount);select

    for (int i=0; i<propertyCount; i++) {model

        objc_property_t  property = propertyArray[i];

        // 2.属性名字

        const char * propertyName = property_getName(property);

        NSString * key = [NSString stringWithUTF8String:propertyName];

        // 3.经过属性名拿到属性值

        id value=[self valueForKey:key];

        NSLog(@"name:%s,value:%@",propertyName,value);

        // 4.判断 值对象是否响应copyWithZone

        if ([value respondsToSelector:@selector(copyWithZone:)]) {

            //5. 设置属性值

            [objCopy setValue:[value copy] forKey:key];

        }else{

            [objCopy setValue:value forKey:key];

        }

    }

    //*****切记须要手动释放

    free(propertyArray);

    return objCopy;

}

相关文章
相关标签/搜索