REF: http://stackoverflow.com/questions/4089238/implementing-nscopying
User.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
//For primitive types (int, char, BOOL and friends) just set the variables to be equal. //for any instance variables that are a subclass of NSObject that supports copying, you can call [thatObject copyWithZone:zone] for the new object - (id)mutableCopyWithZone:(NSZone *)zone { //own object //NSLog(@"User.m - mutableCopyWithZone"); //gives you newly allocated User object id copy = [[self class] allocWithZone:zone]; if(copy) { //theh NSString attributes should be mutable copy //NSString do mutableCopy or mutableCopyWithZone //NSString: mutableCopy gives you back an mutable NSString aka NSMutableString //retains NSMutableString [copy setName: [self.name mutableCopy]]; [copy setEmail: [self.email mutableCopy]]; [copy setPassword: [self.password mutableCopy]]; [copy setAuthToken: [self.authToken mutableCopy]]; [copy setFlowHistoryTableName: [self.flowHistoryTableName mutableCopy]]; //I wanted to do a deep copy of any nsarrays NSArray * deepCopy = [[NSArray alloc] initWithArray:self.listOfStrings copyItems:YES]; [copy setListOfStrings:deepCopy]; //retains a separate address array, with its own data objects } return copy; } - (id)copyWithZone:(NSZone *)zone { //NSLog(@"User.m - copyWithZone"); // Copying code here. //returns the newly allocated User Object here id copy = [[self class] allocWithZone:zone]; if(copy) { //NSString copy gives you back immutable String aka NSString [copy setName:[self.name copy]]; [copy setEmail:[self.email copy]]; [copy setPassword:[self.password copy]]; [copy setAuthToken:[self.authToken copy]]; [copy setFlowHistoryTableName:[self.flowHistoryTableName copy]]; //has own array, but array contents point to same data objects [copy setListOfStrings:[self.listOfStrings copy]]; } return copy; } |