How can I make a deep copy in Objective-C?

前端 未结 6 1677
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 14:03

I\'m learning ios development and I\'m confused with deep copying in Objective-C. For example,I have three class below. Now I want to deep copy ClassA, can anybody teach me

6条回答
  •  一生所求
    2020-12-05 14:54

    I had custom classes with long lists of properties, so I iterated over them:

    @interface MyClass : NSObject 
    
    #import 
    
    -(id) copyWithZone: (NSZone *) zone {
    
        MyClass *myCopy = [[MyClass alloc] init];
    
        //deepCopy
        unsigned int numOfProperties;
        objc_property_t *properties = class_copyPropertyList([self class], &numOfProperties);
    
        for (int i = 0; i < numOfProperties; i++) {
    
           objc_property_t property = properties[i];
           NSString *propertyName = [[NSString alloc]initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
           [adressCopy setValue:[[self valueForKey:propertyName] copy] forKey:propertyName];
        }
        return myCopy;
    }
    

    All customClassProperties will need to implement this as well.

提交回复
热议问题