定義一個Person類
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, strong) NSString *strongName;
@property (nonatomic, copy) NSString *coName;
@end
然后在VC中調(diào)用Person
- (void)testPerson {
NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];
Person *p = [[Person alloc] init];
p.strongName = someName;
p.coName = someName;
[someName setString:@"Debajit"];
// The current value of the Person.name property will be different depending on whether the property is declared retain or copy — it will be @"Debajit" if the property is marked retain, but @"Chris" if the property is marked copy.
// Since in almost all cases you want to prevent mutating an object's attributes behind its back, you should mark the properties representing them copy. (And if you write the setter yourself instead of using @synthesize you should remember to actually use copy instead of retain in it.)
NSLog(@"strongName: %@",p.strongName);
NSLog(@"copyName : %@",p.coName);
}
輸出:
// strongName: Debajit
// copyName : Chris
使用strong修飾的name字符串在賦值之后,如果字符串改變,會影響之前name的內(nèi)容。
使用copy修飾的字符串在值修改之后則不會受到影響。
一個類要使用copy方法需要實(shí)現(xiàn)copyWithZone的協(xié)議
定義一個UserInfo類
#import <Foundation/Foundation.h>
@interface UserInfo : NSObject <NSCopying>
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
- (instancetype)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName;
@end
#import "UserInfo.h"
@implementation UserInfo
- (instancetype)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName {
if (self = [super init]) {
self.firstName = [firstName copy];
self.lastName = [lastName copy];
}
return self;
}
- (id)copyWithZone:(NSZone *)zone {
UserInfo *info = [[[self class] allocWithZone:zone] initWithFirstName:self.firstName lastName:self.lastName];
return info;
}
@end
實(shí)現(xiàn)copyWithZone的協(xié)議方法。
在vc中調(diào)用UserInfo
- (void)testUserInfo {
UserInfo *obj1 = [[UserInfo alloc] initWithFirstName:@"zhang" lastName:@"san"];
NSLog(@"obj1 address : %p %@,%@",obj1,obj1.firstName,obj1.lastName);
UserInfo *copyObj1 = [obj1 copy]; //復(fù)制一個新對象,到一個新的內(nèi)存地址,并把值一并復(fù)制過去。
NSLog(@"copyObj1 address : %p %@,%@",copyObj1,copyObj1.firstName,copyObj1.lastName);
copyObj1.firstName = @"li";
copyObj1.lastName = @"si";
NSLog(@"obj1 address : %p %@,%@",obj1,obj1.firstName,obj1.lastName);
NSLog(@"copyObj1 address : %p %@,%@",copyObj1,copyObj1.firstName,copyObj1.lastName);
輸出:
obj1 address : 0x60400002e8c0 zhang,san
copyObj1 address : 0x60800002fe80 zhang,san
obj1 address : 0x60400002e8c0 zhang,san
copyObj1 address : 0x60800002fe80 li,si
}