Objective-C reference count when pointer set to nil (without ARC)
objective-c, reference-counting, xcode
Solution
No. If you're not using ARC, the object is released when you call `[obj release];`. (ARC inserts these calls for you.) Setting `obj` to `nil` does nothing in terms of memory management (although it does create an object you can no longer reach!).
Basically, in Cocoa without ARC:
- You call `[obj retain]` if you want to take ownership of an object. (`alloc` does this for you.)
- You call `[obj release]` when you want to relinquish ownership of an object. `release` in turn calls `dealloc` when the object's retain count reaches 0.
- You call `[obj autorelease]` when you want to relinquish ownership of an object outside of its current scope. Most commonly, this happens when you return an object from a method (and don't want to retain ownership of it).
Problem
I'm trying to understand how reference counting works, so I disabled ARC and wrote a simple class: (Foo.h is not pasted as it is unmodified) Foo.m ``` @implementation Foo - (instancetype)init { NSLog(@"Init object"); return [super init]; } - (void)dealloc { NSLog(@"Dealloc object"); [super dealloc]; } @end ``` Main.m ``` #import <Foundation/Foundation.h> #import "Foo.h" int main(int argc, const char * argv[]) { Foo *obj = [[Foo alloc] init]; obj = nil; return 0; } ``` Now I expect to see the `dealloc object` log, because the only reference to `Foo` object is gone, but the only message I get is the `init object`. Why don't I see it? Isn't the object released when I assign `obj = nil`?