KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I was reading a little about ARC and I saw this: @interface Address : NSObject { @public NSString *city; } @end @implementation Address - (Address*) init: (NSString*) c { city = c; return self; } - (void) dealloc { NSLog(@"Destroying address: %@", city); } @end @interface Customer : NSObject { NSString *name; Address *addr; } @end @implementation Customer - (Customer*) init: (NSString*) n withAddress: (Address*) a { //Note 1: Automatic retain on assignment name = n; addr = a; return self; } - (void) dealloc { NSLog(@"Destroying: %@", name); //Note 2: Automatic release of member variables } @end Customer* objectReturnTest() { NSString * n = [[NSString alloc] initWithString: @"Billy Bob"]; Address * a = [[Address alloc] init: @"New York City"]; Customer *c = [[Customer alloc] init: n withAddress: a]; //Note 3: ARC will put the returned object in autorelease pool. return c; } A couple of basic things to note here. As "Note 1" says, when an object is assigned to a variable, a call to retain is made automatically. This increments the reference count. As "Note 2" says, when an object is destroyed, all member variable objects are released for you. You no longer have to do that from the dealloc method. Finally, when a method returns a newly created object, ARC will put the returned object in an autorelease pool. This is stated in "Note 3". Now, let’s use the code. int main (int argc, const char * argv[]) { NSString * n = [[NSString alloc] initWithString: @"Johnny Walker"]; Address * a = [[Address alloc] init: @"Miami"]; Customer *c = [[Customer alloc] init: n withAddress: a]; NSLog(@"Before force release"); c = nil; //Force a release NSLog(@"After force release"); @autoreleasepool { Customer *c2 = objectReturnTest(); } NSLog(@"After autorelease pool block."); return 0; } The log output from this code will be:
Tags (comma-separated)
Save Edits
Cancel