在启用ARC的项目中使用alloc,init [英] Using alloc, init in ARC enabled projects

查看:91
本文介绍了在启用ARC的项目中使用alloc,init的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,我正在一个启用了 ARC 的项目中。我知道使用 alloc init 占用了所有权宾语。我知道,如果我创建这样的字符串

Actually I am working on a project with ARC enabled. I know using alloc and init is taking ownership of the object. I know, If I create a string like this

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

然后我需要释放 myString 自己。 如果我启用了ARC,该怎么办?我无法释放自己。那么会造成泄漏吗?还是我不应该创建这样的对象?

then I need to release the myString on myself. What If I am using ARC enabled? I cannot release on myself. So will it create a leak? Or should I don't create object like this?

我也可以创建类似以下代码的字符串。

I can create a string like below code too.

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

但是我需要为支持ARC的项目确切使用哪种类型?如果我使用第一种类型会发生什么?

推荐答案

如果使用ARC,则所有必需的<$ c $编译时会为您添加c> release 调用。

If you use ARC, all the necessary release calls will be added for you when you compile. It will not leak.



The difference between

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

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

是第一个将在最后引用 myString <后自动释放/ code>在该块中,而第二个是自动释放的实例,该实例仅在运行循环结束时释放。没什么大不了,但是如果您使用很多对象,请尽量避免使用自动释放的对象,以保持较低的内存使用率。

is that the first one will automatically released after the last reference to myString in that block, while the second one is an autoreleased instance that will only be released at the end of the run loop. It's not a big difference, but if you're using a lot of objects, try to avoid autoreleased ones to keep memory usage low.

这篇关于在启用ARC的项目中使用alloc,init的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆