在启用ARC的项目中使用alloc,init

其实我正在开发一个启用了ARC的项目。 我知道使用allocinit正在取得对象的ownership 。 我知道,如果我创build一个像这样的string

 NSString *myString = [[NSString alloc]initWithFormat:@"Something"]; 

那么我需要release我自己的myString如果我使用ARC启用? 我无法释放自己。 那么它会造成泄漏? 还是我不应该这样创build对象?

我也可以像下面的代码一样创build一个string。

 NSString *myString = [NSString stringWithFormat:@"Something"]; 

但是,我需要准确使用ARC启用项目的types? 如果我使用第一种types会发生什么?

如果您使用ARC,则在编译时将为您添加所有必要的release调用。 它不会泄漏。

和…之间的不同

 NSString *myString = [[NSString alloc]initWithFormat:@"Something"]; 

 NSString *myString = [NSString stringWithFormat:@"Something"]; 

第一个是在该块中最后一次引用myString之后自动释放的,而第二个是仅在运行循环结束时释放的自动释放实例。 这不是一个很大的区别,但是如果你使用了很多的对象,尽量避免自动发布的对象来保持内存使用率低。

ARC负责内存pipe理,所以不需要担心在你的myStringvariables上调用release ,ARC会为你做。 另外作为一个build议,我会build议使用便利的方法来创build你的对象,如

[NSString stringWithFormat:@"Something"];

将string指针设置为零就足以将其释放。
你也可以做同样的事情,你可以在没有ARC的情况下做,但是如果你没有明确地做任何事情,ARC将会为你pipe理(几乎)所有的事情。

所以释放它,你把它设置为零,让我们看看你还能做什么:

  NSString* str= [[NSString alloc]initWithUTF8String: "Hello"]; // here the retain count of str is 1 __unsafe_unretained NSString* string= str; // again 1 because string is __unsafe_unretained void* data= (__bridge_retained void*) string; // data retains the string, so the retain count is to 2 // This is useful in the case that you have to pass an objective-c object // through a void pointer.You could also say NSString* data= string; str=nil; // Here the retain count of str is 1 NSLog(@"%@",(__bridge NSString*)data); 

UPDATE

这就是为什么有时你不会注意到一个对象被释放:

  NSString* str= [[NSString alloc]initWithString: @"hey"]; __unsafe_unretained NSString* str2=str; str=nil; NSLog(@"%@",str2); 

在这种情况下str = [[NSString alloc] initWithString:@“hey”]等于str = @“hey”,不同之处在于str是自动释放而不是释放的。但是编译器优化了str = @“hello “,所以如果你在一个autorelease块内,你不会有任何问题,str2将被正确打印。
这就是为什么我使用initWithUTF8String,以避免编译器优化。