用copy修飾的區(qū)別,發(fā)生在用NSMutableString類型給NSString類型賦值時,為了防止賦值的屬性內(nèi)容被無意中修改,所以用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的值變化了。
轉(zhuǎn)自:
關于OC對象屬性中的NSString類型為什么用copy修飾