IOS @proporty 關鍵字(一)retain strong

FlyLolo發表於2015-04-28
@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.

相關文章