Home > Software engineering >  Release allocated or initialized object in objective-c?
Release allocated or initialized object in objective-c?

Time:11-21

Memory management says we must release an object created with alloc. Consider this typical example code.

XYZClass *obj = [[XYZClass alloc] init];
// use obj
[obj release];

But in this example, obj may not be the object returned from alloc, as Apple's documentation says

Note: It’s possible for init to return a different object than was created by alloc, so it’s best practice to nest the calls as shown.

So this typical example seems to release the object returned from init, breaking memory management rules, and not release the object returned from alloc, further breaking the rules. How is this typical example valid?

CodePudding user response:

First of all you code uses manual memory management, that is something I would not recommend, since Xcode 4.2 for OS X v10.6 and v10.7 (64-bit applications) and for iOS 4 and iOS we have support for Automatic Reference Counting (ARC) is a compiler feature that provides automatic memory management of Objective-C objects. See Transitioning to ARC Release Notes :

Instead of your having to remember when to use retain, release, and autorelease, ARC evaluates the lifetime requirements of your objects and automatically inserts appropriate memory management calls for you at compile time. The compiler also generates appropriate dealloc methods for you.

With regards to your specific question, the fact that init might return a different object does not break the memory management, because that different object will use the same allocation. This is quite common for class clusters that the initializer might return a internal subclass.

  • Related