使用 NSMutableArray 保留和 self
在我的 .h 文件中,我定义了一个 NSMutableArray *locationsArray ,其属性如下
@property (nonatomic, retain) NSMutableArray *locationsArray
在我的 .m 文件中,我显示了一个表视图,该视图加载得很好,直到我尝试滚动,此时我因访问错误而崩溃。这是由于没有保留locationsArray。
这行代码解决了我在 .m 中的问题
locationsArray = [[Locations loadLocations] retain] (#1)
这行代码也解决了同样的问题
self.locationsArray = Locations.loadLocations (#2)
我有几个问题需要澄清
- 这是设置此值的正确方法吗?我应该执行
alloc< /code>
init
,alloc initwithArray
? - 来自java世界,我理解
self
是这样的,或者至少我认为我做到了......在objective C中,没有self的
。locationsArray
有什么不同如果我不添加保留,则不会保留
显然我已经让它工作了,但花了一段时间,而且我仍然有点困惑为什么。任何帮助将不胜感激。
In my .h file I have a NSMutableArray *locationsArray defined with a property as follows
@property (nonatomic, retain) NSMutableArray *locationsArray
In my .m file I was displaying a table view, this loaded fine until I tried to roll-up at which point I it crashed with bad access. This was due to the locationsArray not being retained.
This line of code fixed my problem in the .m
locationsArray = [[Locations loadLocations] retain] (#1)
This line of code also fixed the same problem
self.locationsArray = Locations.loadLocations (#2)
I have a couple of questions I need clarification on
- is this the correct way to set this value, should I be doing an
alloc
init
,alloc initwithArray
? - Comming from a java world I understand
self
is this, or at least I thought I did...What is different in objective C that thelocationsArray
without theself
is not being retained without me adding the retain.
Obviously I got it working but it took as while and am still a little confused as to why. any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,如果直接设置实例变量(locationsArray),则需要保留该值以保留它。您可以像以前那样执行此操作,也可以直接分配/初始化它,这也意味着您拥有它的保留所有权。
self
确实相当于其他 OO 语言中的this
。但是 Obj-C 中存在语义差异,在第一个示例中引用“裸”ivar 与在第二个示例中将其引用为 self.locationsArray 之间存在语义差异。前者的行为如您想象的那样,但后者实际上是[self setLocationsArray: ... ]
的语法快捷方式,它会自动为您保留,因为您已将该属性标记为保留
。最后一点确实很微妙,并且(在我看来)不是预期的或明显的行为。如果您仍然不清楚,请返回 Apple 文档。得到这个真的很重要。
Yes, if you set the instance variable (locationsArray) directly, you need to retain the value to keep it. You can either do that as you've done, or alloc/init it directly, which also means that you have a retain ownership of it.
self
is indeed equivalent tothis
in other OO languages. But there's a semantic difference in Obj-C between referring to an ivar "naked" like in your first example, and referring to it asself.locationsArray
in the second. The former behaves how you'd imagine, but the latter is actually a syntactic shortcut for[self setLocationsArray: ... ]
which does the retain automatically for you, because you've marked the property as beingretain
.This last point is really subtle, and (to my view) not expected or obvious behavior. If you're still fuzzy on it, go back to the Apple docs. Really important to get this.