CourtneyJo Wright
17 year old girl
more famous quotes
For those coming to the iPhone (and Obj-C/Cocoa) platform, especially those coming from any platform with garbage collection will definitely get caught out by Cocoa’s memory management model. This will probably hit those developing using the iPhone SDK hard, with its limited memory catching leaks will be ever more important as when memory runs low your app will have to clean up after itself and exit
.
For those reading Cocoa code for the first few times calls to methods such as -retain, -release and -autorelease might seem somewhat bizarre, but they form the basis of Cocoa memory management. Cocoa uses reference counting to keep track of memory and the code that uses it, a common practice in low memory devices. These calls are all you need to make sure you aren’t causing memory leaks in your code.
| Method | Description |
|---|---|
-retain | increases the reference count of an object (by 1) |
-release | decreases the reference count of an object |
-autorelease | decreases the reference count of an object by 1 when possible |
-alloc | allocates memory for an object, and returns it with retain count of 1 |
-copy | makes a copy of an object, and returns it with retain count of 1 |
Good things come in three, so here are the three golden rules for memory management for iPhone development
-copy, -alloc and -retain should be balanced by use of -release and -autorelease.-dealloc method to release the instance variables you own when your class is destroyedMaintaining the reference counts for an object
1.- (void)helloWorld{2.NSString *string;3.//alloc the memory for sting object4.string = [[NSString alloc] initWithString:@"Hello World"];5.// we created string with alloc so we need to release it so the6.//referance count for this code block match7.[string release];8.}Creating an object using a convienience constructor, autrelease is used.
1.- (void)helloWorld2.{3.NSString *string;4.// object is created with a convenience constructor, will be autoreleased5.string = [NSString stringWithFormat:@"Hello"];6.// autorelease, no need for release7.}Working with arrays, and objects stored in arrays. Objects placed inside an array in can be released after addition since the array object will add 1 to the reference count
1.NSMutableArray *array;2.int i;3.for (i = 0; i <>4.{5.NSNumber *n = [[NSNumber alloc] initWithInt: i];6.[array addObject: n];7.[n release];8.}