@interface User : NSObject @property (nonatomic,retain) NSString* tRetain; @property (nonatomic,assign) NSString* tAssign; @property (nonatomic,copy) NSString* tcopy; @end
类User有个属性tRetain, 只是测试就用NSString类型了(此类型一般用copy, 因为可能是个NSMutableString,不希望在赋值后被其他地方修改内容)。
User* user = [[User alloc]init]; NSString* testRetain = [NSString stringWithFormat:@"retain"]; NSLog(@"testRetain.retainCount=%lu",(unsigned long)testRetain.retainCount); //1 user.tRetain = testRetain; NSLog(@"testRetain.retainCount=%lu",(unsigned long)testRetain.retainCount); //2 NSLog(@"user.tRetain.retainCount=%lu",(unsigned long)user.tRetain.retainCount); //2 NSString* testRetain2 = @"retain2"; NSLog(@"testRetain2.retainCount=%lu",(unsigned long)testRetain2.retainCount); //4294967295 自动释放对象 返回max unsigned long user.tRetain = testRetain2; NSLog(@"testRetain.retainCount=%lu",(unsigned long)testRetain.retainCount); //1 NSLog(@"testRetain2.retainCount=%lu",(unsigned long)testRetain2.retainCount); //4294967295 NSLog(@"user.RetainValue.retainCount=%lu",(unsigned long)user.tRetain.retainCount); //4294967295 NSString* testRetain3 = [NSString stringWithFormat: @"retain3"]; NSLog(@"testRetain3.retainCount=%lu",(unsigned long)testRetain3.retainCount); //1 [testRetain3 retain]; NSLog(@"testRetain3.retainCount=%lu",(unsigned long)testRetain3.retainCount); //2 NSString* testRetain4 = [NSString stringWithString:testRetain3]; NSLog(@"testRetain3.retainCount=%lu",(unsigned long)testRetain3.retainCount); //3 NSLog(@"testRetain4.retainCount=%lu",(unsigned long)testRetain4.retainCount); //3
strong是ARC后引入的关键字, 在ARC环境中等同于Retain。
NSSring* str = [NSString stringWithString:字符串]; 此方法相当于上文对一个retain属性赋值。 若后面的字符串参数的计数为4294967295,则str的计数也是。 若字符串参数可计数, 例如1, 则执行后计数加1.