1 Deep copy: Content copy, source object and replica object refers to two different objects, source object reference counter is unchanged, replica object reference counter is 1
2 Shallow copy: pointer copy, source object and replica object refer to the same object, object reference counter +1, equivalent to retain
3 Only immutable objects create immutable replicas (copy) is shallow copy, others are deep copy
Use of the Copy keyword
Usually we use retain count +1 in the transfer between objects, this method is applicable to when the value of an object's property changes, the reference to the object's different pointers will change at the same time, because the two pointers to the same memory address,
However, if the requirement is that when the object property value of a pointer is changed and does not affect the other object, then two different memory addresses need to be allocated, that is, we can not adopt the Retain keyword, but to use the Copy keyword, Because the Copy keyword re-creates a new object when it is copied. Illustrate the use of copy
Create a person class here
Person.h, Code:
@interface Person:nsobject <nscopying>{
NSString *name;
NSString *email;
}
@property (nonatomic, retain) NSString *name;
@property (Nonatomic,retain) NSString *email;
@end
PERSON.M file
#import "Person.h"
@synthesize Name,email;
-(ID) Initwithname: (NSString *) thename andemail: (NSString *) theemail
{
self = [super init];
if (self) {
Self.name = thename;
Self.email = Theemail;
}
}
-(ID) Copywithzone: (Nszone *) zone
{
Person *aperson = [[Person Allocwithzone:zone] Initwithname:[self name] andemail:[self email]];
return Aperson;
}
-(void) Delloc
{
[Name release];
[Email release];
[Super Dealloc];
}
Here's a little bit of information
Copy between objects, first need class is inherit from NSObject, second need implement <NSCoding> protocol, finally implement in method
-(ID) Copywithzone: (Nszone *) Zone method
If you do not have this method then in the Copy object, the program goes down directly and prompts the person class not to find the Copywithzone method.
It is also important to note that, usually copy between Nsarray, is the copy of the retain mode, that is, the direct reference coefficient of +1,
The following code:
Nsarray *array1 = [[Nsarray alloc] initwithobjects:person1,person2,person3,nil];
Nsmutablearray *array2 = [array1 copy]; or use
Nsmutablearray *array2 =[[Nsmutablearray alloc] initwitharray:array1];
If you want to use two different memory, then you need to use deep copy to Nsarray, for example:
Nsarray *array1 = [[Nsarray alloc] initwithobjects:person1,person2,person3,nil];
Nsmutablearray *array2 = [[Nsmutablearray alloc] Initwitharray:array1 Copyitems:yes];
IOS copy/retain/assign