使用 ARC 时将属性分配给自动释放的初始化程序的结果是否安全?

发布于 2024-12-27 10:42:05 字数 402 浏览 3 评论 0原文

假设我有一个像这样的强大属性:

  @interface Foo
    @property (strong, nonatomic) NSArray *myArray;
  @end

并且,在我的初始化程序中,我像这样设置 myArray:

myArray = [NSArray array];

这安全吗? ARC 会为我妥善保留 myArray 吗?

我问的原因是我有一个项目,在这种情况下 myArray 没有正确保留,并且我的内存访问很糟糕。

但是,如果我使用的

 myArray = [[NSArray alloc] init];

话一切都很好。

Let's say I have a strong property like so:

  @interface Foo
    @property (strong, nonatomic) NSArray *myArray;
  @end

And, in my initializer, I set myArray like so:

myArray = [NSArray array];

Is this safe? Will ARC take care of properly retaining myArray for me?

The reason I ask is that I have a project where myArray isn't properly retained in this scenario, and I get a bad memory access down the road.

But, if I use

 myArray = [[NSArray alloc] init];

then all is well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

栖迟 2025-01-03 10:42:05

是的,ARC会自动为您保留它。

考虑 ARC 的方式是这样的:如果你有一个指向对象的强指针,那么它就保证保持活动状态。当指向某个对象的所有指针(好吧,所有指针)都消失时,该对象就会消亡。

从问题的描述来看,听起来您执行该代码的文件中未正确启用 ARC。无论如何,我建议使用“Zombies”模板通过 Instruments 运行您的应用程序。这将使您看到该对象的完整保留/释放历史记录,并且您应该能够找出哪里出了问题。

Yes, ARC will automatically retain it for you.

The way to think of ARC is this: If you have a strong pointer to an object, then it is guaranteed to stay alive. When all pointers (well, all strong pointers) to an object go away, the object will die.

From the description of your problem, it sounds like ARC isn't properly enabled in the file where you're executing that code. Regardless, I'd recommend running your app with Instruments, using the "Zombies" template. That will let you see the full retain/release history of that object, and you should be able to figure out where things are going wrong.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文