在可可中保留信息?
我对 Cocoa 还是个新手,对内存管理不太了解。我阅读了苹果的文档,但仍然感到困惑。我的问题是,如果我在 - (void)dowhatever
中设置变量的值,当 dowhatever
结束时,变量的内容会被删除吗?如果是这样,是否有一种方法(无需写入文件)可以用来保留变量内容?
感谢您的帮助
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
void
是一种类型。它没有开始也没有结束。具体来说,它是
dowhatever
方法的返回类型。如果dowhatever
返回一个值,则该返回值的类型将是void
所在的位置;例如,它会显示- (NSUInteger) doWhatever
。那里有void
意味着该方法不返回值。另请参阅 Objective-C 2.0 编程语言文档。
如果它是局部变量,那么当方法返回时,该变量将不再存在。
只要该变量所属的实例(对象)存在,实例变量就存在,即直到该实例被释放为止。
Objective-C 文档中也介绍了实例变量。
如果您只是需要将对象返回给调用者,请保留它并自动释放它。有关详细信息,请参阅 Cocoa 内存管理编程指南 。
如果这不是您正在做的事情,那么问题就变成了为什么您需要该对象保持活动状态。
从对象的角度思考:一个对象可能拥有某些其他对象,并且它拥有的每个对象都有一个实例变量*。只要您明确所有权并在代码中维护它们,对象的生命周期就可以发挥作用。
如果对象 A 需要另一个对象 B,那么 A 应该拥有 B。这种所有权不是排他性的;而是具有排他性的。它可以共同拥有 B。但它需要至少共同拥有 B;只要 B 至少有一个所有者,它就会一直存在。
《内存管理指南》中也对此进行了介绍。有关对象之间关系的其他示例,您应该浏览 Cocoa 基础知识指南,特别是关于 的章节Cocoa 的设计模式,您可能需要查看示例代码以查看实践中演示的这些模式。
*它还可以拥有不属于它的对象的实例变量,例如委托。您可以为不属于您的对象拥有一个实例变量,但如果您确实拥有它,则应该为它拥有一个实例变量。
void
is a type. It has no beginning and no end.Specifically, it's the return type of the
dowhatever
method. Ifdowhatever
returned a value, the type of that return value would be where you havevoid
; it would say, for example,- (NSUInteger) doWhatever
. Havingvoid
there means that the method does not return a value.See also the Objective-C 2.0 Programming Language document.
If it's a local variable, then the variable will cease to exist when the method returns.
An instance variable exists as long as the instance (object) that the variable is a part of exists—that is, until the instance is deallocated.
Instance variables are also covered in the Objective-C documentation.
If you simply need to return the object to your caller, retain it and autorelease it. See the Memory Management Programming Guide for Cocoa for more info.
If that's not what you're doing, then the question becomes why you need the object to stay alive.
Think in terms of objects: An object may own certain other objects, and has an instance variable for every object it owns*. As long as you have your ownerships straight and uphold them in code, objects' lifetimes just work.
If object A needs another object B, then A should own B. This ownership isn't exclusive; it can co-own B. But it needs to at least co-own B; B will remain alive as long as it has at least one owner.
That's also covered in the Memory Management Guide. For other examples of relationships between objects, you should flip through the Cocoa Fundamentals Guide, particularly the chapter on Cocoa's design patterns, and you may want to look through sample code to see those patterns demonstrated in practice.
*It can also have instance variables for objects it doesn't own, such as delegates. You can have an instance variable for an object you don't own, but if you do own it, you should have an instance variable for it.