-
Ownership
- You own any object you create
- You can take ownership of an object using retain
- You must relinquish ownership of objects you own when you’re finished with them
- You must not relinquish ownership of an object you do not own
-
Alloc
-
便利寫法
- NSNumber *zero = [NSNumber numberWithInteger:0];
- 會Autorelease
-
標準寫法
- NSNumber *zero = [[NSNumber alloc] initWithInteger:0];
- 需要自己release
-
Copy
-
Copy non-pointer iVar
- Deep copy only
- int a = b;
-
Copy pointer iVar
-
Deep Copy
- Copy the data
- Element *a = [b copy];
-
Shallow Copy
- Copy the pointer
- Element *a = b;
-
Array
- Add to an Array means "Copy"
- Remove from an Array means "Release"
- objectAtIndex only get the pointer
-
Reference
-
Strong reference
-
Retain
- Object will be dealloc if ALL the strong references are released
- Retain is preventing object from being released
-
Weak reference
- table data sources
- outline view items
- notification observers
- delegates
-
Release
-
Autorelease
- Every thread needs its own autorelease pool
- To clean the autorelease pool, use "drain" is better than use "release", drain will trigger garbage collection in some case
- Manual release
-
Accessor Methods
- Why use it? Just better, clear and avoid bugs
-
How
-
分支主題 2
-
Retain
- Retain and autorelease the value before return
return [[title retain] autorelease];
- Release the old value and retain new value
if (title != newTitle) {
[title release];
title = [newTitle retain]; // or copy depending on your needs
}
-
Assign
- Return the value
return title;
- Autorelease old value and retain the new value
[title autorelease];
title = [newTitle retain];
-
Assign
- Return the value
return title;
- Release the old value and retain new value
if (title != newTitle) {
[title release];
title = [newTitle retain]; // or copy depending on your needs
}
-
Copy
- - (NSString *)name {
return [[name copy] autorelease];
}
- - (void)setName:(NSString *)aName {
[name autorelease];
name = [aName copy];
}
-
Object in Nib file
- Retain and Autorelease
-
DidReceiveMemoryWarning
- [self setView:nil];
- - (void)viewDidUnload {
self.anOutlet = nil;
[super viewDidUnload];
}