Does autorelease guaranty that at the end of blocks the object will get released?
Or is it better to 开发者_运维技巧manually release objects?
It guarantees it will be released sometime after the block executes, not necessarily immediately after. It's up to the runtime to determine exactly when.
It's not big deal unless you're doing something with a lot of autoreleased variables, like creating them in a big loop, or if you're creating large autoreleased objects, like UIImages. In these cases, you should manually release when you're through, otherwise autorelease is perfectly acceptable.
If an object is autorelease
d, you MUST not manually release
it (unless it is retain
ed of course). The NSAutoRelease pool which is part of the UIKit event handler will release
it for you. If you were to manually release
the object, the pool may cause a crash or other undefined behavior as the object will be doubly-release
d.
If there are cases where you generate a lot of objects or use a lot of memory in objects, you can pre-emptively autorelease
them (perhaps in your loop) by creating your own NSAutoReleasePool
- pools can be nested.
It's better to release objects rather than autorelease, unless of course you have an explicit reason to use autorelease, for example use autorelease when returning an object the method retained and you can't avoid it.
Basically autorelease should be used as an excuse to completely avoid memory management. You want to release objects as soon as you possible can. Autorelease just says the object will be released some time in the future.
精彩评论