1. 程式人生 > >關於OC物件屬性中的NSString型別為什麼用copy修飾

關於OC物件屬性中的NSString型別為什麼用copy修飾

用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 char * argv[]) {
    @autoreleasepool {
        
        CopyStr *str = [[CopyStr alloc] init];
        
        [str testStr];
    }
    return 0;
}
可以看出,當用NSMutableString型別mString的物件給NSString型別str的物件賦值時,在mString改變後,用copy修飾的NSString物件strCopy的值不變,而用strong修飾的NSString物件strStrong的值變化了。