4 ms·
To me, not familiar with ObjC/OSX memory management, the last sentence reads like "...it's not a big deal after all. If you malloc/fopen something, make sure yo
by limmeau 16y ago
To me, not familiar with ObjC/OSX memory management, the last sentence reads like "...it's not a big deal after all. If you malloc/fopen something, make sure you free/fclose it."
Could you explain the difference?
- Leynos 16y agoRather than being responsible for ultimately disposing of an object, they need only tell the runtime that it is no longer needed. A retain count (a count on other parties with an interest in an object) is maintained by the runtime. When the retain count reaches zero, the object is freed. When an object is created (using alloc or copy), it has a retain count of 1. Another object can express its interest by calling the "retain" method. When it is done, the "release" method should be called. If an object is being returned, but shouldn't be freed right away, there is a mechanism called "autorelease" where the call to release is delayed until the end of the current runloop, giving other objects a chance to retain the returned object.
- blub 16y agoThis is almost as prone to failure as malloc/free, you still have to call functions by hand.
- Leynos 16y agoIndeed. I've become quite enamoured of late with the automatic reference counting in the Boost C++ library as a happy medium between GC and manual reference counting. Of course, ObjC has no static allocation, so that can't be done here.
- pornel 16y agoIf find it much easier than malloc/free. Cocoa uses autorelease pool for short-lived objects, so most of the time you don't have to free them. For long-lived objects you can use synthesized properties which handle retain/release for you. In other cases you "guard" your use of object with retain/release. You can use these in pairs in the same place, rather than having malloc() in one part of the program, and free() in another. You can freely pass reference to an object without worrying that you might free it while it's still referenced somewhere else. You don't have to think about ownership of an object.
- SoftwareMaven 16y agoThe difference is there is core support for reference counting and cleaning up unreferenced items. Any time you are using an object, you grab a reference; at the end of a call chain (managed as a part of message passing), if an item has no references, it will be deleted automatically. With C, you are forced to care who actually allocated something and figure out a protocol for dealing with getting it released. With Objective C, I can allocate something, hold my reference for the duration of the call, release my reference and return it. If the caller wants a reference, they can then grab it; if they don't, it will get deleted.
- loewenskind 16y agoObjC on iOS is still memory management but the advantages over C are: reference counting (makes composition easier) and a defined protocol for when references wont be used anymore.