Reputation: 6331
I studied a tutorial about Objective-C memory management and i think i understand how it works. However, i wonder why autorelease-pools were created to work the way they do. As far as i understand the autorelease message is mostly used when returning objects from functions, since the callee can't be sure that the caller will actually store the result in a variable (which would be necessary to release the returned object later on). I have a theory that this concept was made back in the day when Objective-C was merely a preprocessor. A compiler instead would be aware of an unassigned return value and could silently auto-insert a release for the returned object (this behaviour would imply that every assigned return value would have to be released manually)
So my questions:
Upvotes: 3
Views: 2562
Reputation:
Your explanation is partially correct. Yes, autorelease pools are mainly used to return a non-owned object from a function or method: you can't release the object inside your method or the caller couldn't use it. You could require callers to accept ownership of an object returned from a function or method, as Core Foundation does with its Create rule, but Foundation introduced the autorelease pool and avoids this requirement.
However this is not related to Objective-C being a preprocessor or part of the compiler. It's dependent purely on the memory management policy in use by the framework and language.
malloc
/free
system. It has no autorelease pool; the programmer frees an object when they know it's done with.Your suggestion that an object should be retained only when it's aliased to a named variable visible to the compiler will not work in the general case. The programmer could keep an unnamed reference to the object (e.g. in a collection or via an association), or they could create an object that must stay around despite there being no alias to it.
[*] In fact the reference-counted system existed in Mach Kit as NXReference (and was used in other frameworks, like Indexing Kit) earlier, but when it became part of Foundation it became conventional for all Objective-C classes (in NeXTStep and WO applications, and hence in Mac and iOS apps) to use reference-counted memory management.
Upvotes: 7