Objective-c 属性和内存管理

发布于 2024-12-28 00:20:13 字数 438 浏览 1 评论 0原文

只是一个简单的问题: 我有一个数组,将其命名为 sourceArray。该数组中有字典。 我有一个保留属性,用于保存数组中的一项。 当我从数组中设置属性时,它工作正常。 但是,当我将其设置为其他项目并返回到第一个项目时,我收到了 bad_access 异常,因为第一个项目已被释放。

我的问题是为什么?在源数组中,项目被保留,当我设置它保留的属性时。当我再次设置它时,设置器会释放旧值并保留新值。我猜...但显然这样不行。

例子:

 [self setProperty:[sourceArray objectAtIndex:0]];
 [self setProperty:[sourceArray objectAtIndex:1]];
 [self setProperty:[sourceArray objectAtIndex:0]]; ---> Exception

Just a quick question:
I've got an array, name it sourceArray. This array has dictionaries in it.
I've got a retained property, which is used to hold one item from the array.
When I set the property from the array it works fine.
But, when I set it with an other item, and back to the first, I got a bad_access exception, since the first item has been released.

My question is why? In the source array, items are retained, and when I set the property it retains to. When I set it again, the setter release the old value, and retain the new. I guess... But apparently it doesn't work in this way.

Example:

 [self setProperty:[sourceArray objectAtIndex:0]];
 [self setProperty:[sourceArray objectAtIndex:1]];
 [self setProperty:[sourceArray objectAtIndex:0]]; ---> Exception

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

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

发布评论

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

评论(1

瘫痪情歌 2025-01-04 00:20:13

我明白了。
在其他地方,我有一句话:

property = [sourceArray objectAtIndex:0];

看起来当我使用set方法时,旧值被释放,无论它没有被保留(因为在第一次,我没有使用set方法)。
我的错...

I've got it.
In other place, I've a line:

property = [sourceArray objectAtIndex:0];

It looks like when I use the set method, the old value get released, no matter that it hasn't been retained (since in the first time, I didn't use the set method).
My fault...

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