ClassA.h
#import <Foundation/Foundation.h>
@interface ClassA : NSObject
@property (nonatomic,weak) NSString *name;
@end
main.m
#import <Foundation/Foundation.h>
#import "ClassA.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSMutableString *str = [[NSMutableString alloc]initWithString:@"www.google.com"];
ClassA *classA = [[ClassA alloc] init];
classA.name = str;
[str appendString:@" plus"];
NSLog(@"%@, %p", classA.name, classA.name);
NSLog(@"%@, %p", str, str);
}
return 0;
}
輸出結果:
www.google.com plus, 0x100406aa0
www.google.com plus, 0x100406aa0
如果把weak或strong改為copy,由淺復制變成深復制
@property (nonatomic,weak) NSString *name;
@property (nonatomic,copy) NSString *name;
輸出結果:
www.google.com, 0x7fff79f8d3c0
www.google.com plus, 0x100406aa0
針對指針型對象的拷貝,有淺復制和深復制兩種。
淺復制:將原始對象的指針值復制到副本中,即指針拷貝,原始對象和副本共享引用的數據;相當于創建了一個文件的快捷方式。
深復制:復制原始對象指針所引用的數據,并將其賦給副本對象,即內容拷貝,相當于創建了一份新的文件。
例如,當我們為一個類的屬性添加copy關鍵字時,那么對這個屬性賦值時(即:調用setter方法),就會執行深拷貝操作。當我們把屬性關鍵字改為strong或者weak時,那么對這個屬性賦值時,就會執行淺拷貝(只拷貝指針地址)。
NSString *string = @"test";
NSString *string1 = [string copy];
NSString *string2 = [string mutableCopy];
copy->復制指針(創建一個指針指向原始的內存地址)
mutableCopy->復制指針及內容(創建新的內存地址)
string:[0x100001058]test
string1:[0x100001058]test
string2:[0x100201600]test