开发者

Retain information in cocoa?

I'm still new to Cocoa and don't know much about memory management. I read up on Apple's documentation but I'm still confused. My question is if I set the value of a variable in a - (void)dowhatever when dowhatever ends, will the contents of the variable be erased? If so is there a method (wit开发者_开发问答hout writing to a file) that I can use to retain the variable contents?

Thanks for any help


My question is if I set the value of a variable in a - (void)dowhatever when the void ends, …

void is a type. It has no beginning and no end.

Specifically, it's the return type of the dowhatever method. If dowhatever returned a value, the type of that return value would be where you have void; it would say, for example, - (NSUInteger) doWhatever. Having void there means that the method does not return a value.

See also the Objective-C 2.0 Programming Language document.

… will the contents of the variable be erased?

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 so is there a method (without writing to a file) that I can use to retain the variable contents?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜