用copy修饰的区别,发生在用NSMutableString类型给NSString类型赋值时,为了防止赋值的属性内容被无意中修改,所以用copy修饰。
#import <Foundation/Foundation.h>
@interface CopyStr : NSObject
@property (nonatomic, copy) NSString *strCopy;
@property (nonatomic, strong) NSString *strStrong;
- (void)testStr;
@end
#import "CopyStr.h"
@implementation CopyStr
- (void)testStr
{
NSMutableString *mString = [NSMutableString string];
[mString setString:@"original"];
self.strCopy = mString;
self.strStrong = mString;
NSLog(@"strCopy = %@", self.strCopy); // strCopy = original
NSLog(@"strStrong = %@", self.strStrong); // strCopy = original
[mString setString:@"changed"];
NSLog(@"strCopy = %@", self.strCopy); // strCopy = original
NSLog(@"strStrong = %@", self.strStrong); // strCopy = changed
}
#import <Foundation/Foundation.h>
#import "CopyStr.h"
int main(int argc, const charchar * argv[]) {
@autoreleasepool {
CopyStr *str = [[CopyStr alloc] init];
[str testStr];
}
return 0;
}
可以看出,当用NSMutableString类型mString的对象给NSString类型str的对象赋值时,在mString改变后,用copy修饰的NSString对象strCopy的值不变,而用strong修饰的NSString对象strStrong的值变化了。
转自:
关于OC对象属性中的NSString类型为什么用copy修饰