下面提到的NSStrings分配的保留计数是多少?

时间:2013-04-19 02:26:07

标签: ios objective-c nsstring release

这里我以十种不同的方式分配了NSString个变量,我想知道所有变量的保留计数。

@interface SomeClass : NSObject 
{ 
   NSString *str1; 
   NSString *str2;
} 
@property (nonatomic, retain) NSString* str1;
@property (nonatomic, copy) NSString * str2; 


 - str1 =@"hello";

 - self.str1 = @"hello";

 - str1 = [[NSString alloc]init];

 - self.str4 = [[NSString alloc]init];

 - str1 = [[[NSString alloc]init]autorelease];

 - self.str1 = [[[NSString alloc]init]autorelease];

 - str1 = [[NSString alloc]initWithString:@"hello"];

 - self.str1 = [[NSString alloc]initWithString:@"hello"];

 - str1 = [[[NSString alloc]initWithString:@"hello"]autorelease];

 - self.str1 = [[[NSString alloc]initWithString:@"hello"]autorelease];

上面提到的NSString分配的保留计数是多少?我怎么知道它们的保留计数对于所有这些都保持不同?

2 个答案:

答案 0 :(得分:4)

虽然这看起来像是家庭作业,但您可以在每个字符串上调用retainCount以获得实际值的近似值。您绝对不应该将此方法用于生产应用程序中的任何逻辑(请参阅http://whentouseretaincount.com)!文档说明:

  

特别注意事项

     

此方法在调试内存管理问题时没有任何价值。因为任何数量的框架对象可能保留了一个对象以保存对它的引用,而同时自动释放池可能在对象上保留任意数量的延迟版本,所以您不太可能从此获取有用信息方法

答案 1 :(得分:4)

我假设它们是在某些SomeClass方法中访问的。变体:

// replace str1 with str2(copy), retain count will remain the same
str1 = @"hello";
self.str1 = @"hello"
str1 = [[NSString alloc]initWithString:@"hello"];
self.str1 = [[NSString alloc]initWithString:@"hello"];
str1 = [[[NSString alloc]initWithString:@"hello"]autorelease];
self.str1 = [[[NSString alloc]initWithString:@"hello"]autorelease];

在这里,您将获得一个巨大的值,比如UINT_MAX,编译器将优化您的代码(您传递文字值,NSString是不可变的),这些对象将是不可释放的。

self.str1 = [[NSString alloc] initWithFormat:@"a string %d", 5]; // with autorelease or not - the same

在这里,你最终得到一个释放计数= 2,你分配字符串+1,你指定一个保留属性+1 = 2.

self.str2 = [[NSString alloc] initWithFormat:@"a string %d", 5]; // with autorelease or not - the same

在这里你最终得到一个释放计数= 1,你分配字符串+1,你分配一个复制属性,从而创建一个创建的字符串= 1的副本。

在所有其他情况下,你最终会释放次数= 1,自动释放不会增加保留计数,当池耗尽时它只会减1。

请记住:

  1. 不要依赖retainCount,
  2. 当您通过alloc,new,copy,mutable copy创建对象时,您有责任释放它。如果你用[NSString string]创建对象,它将被自动释放。
  3. 保留属性保留对象,复制属性副本对象,属性通常通过点表示法(self.property等)使用(还有合成的%Property%和%property%方法,所以self.property = ...(通常)与[self setProperty:...])
  4. 相同
  5. 是时候搬到ARC了。所以,如果你能,你应该。