Memory management
basic principle
In objective-c, the memory is managed by yourself, you have to dispose of the object you created.
For example:
-void foo
{
Dog *anDog = [[Dog alloc]init];
NSLog(@”%@”, anDog.name);
[anDog release];
}
In above example, the alloc/release pair is something like new/delete pair in C++, but the things behind the code is very different. In OC(objecitve-c), the alloc/release will add/reduce the retainCount of the object, once the retainCount becomes 0, the memory of the object is collected by system.
Besides alloc, the copy and retain messages also can increase the retain count of object. And autorelease messages can add the object to autorelease pool and release the object when the pool is drained (or release - to understand the difference, see "Garbage Collection"). An object may receive autorelease message several times before it is really deallocated.for example:
-(void)foo
{
NSString *dogName = [[NSString stringWithFormat:@”kala”]];
[dogName autorelease];
}
In this case, the object will receive 2 times release messages when the pool is drained.
A question: if there are many objects stay in the autorelease pool, what will happen?
Local variables
In OC, the compiler can't generate object creation and initialization code for you, so you can't use local object like this:
-void foo
{
Dog anDog; //error: statically allocated instance of Objective-C.
NSLog(@”%@”, anDog.name);
}
as a result, you have to alloc and release the local variable by yourself.
Member variables and properties
For the member variable, the basic memory management principle is very similar with local variable, but to unify the process to access member variables, it's better to use property to access the member variable, since it can release the old reference and retain the new one automatically.
Other Questions:
Why the grammar of NSLog is C-Style?
when to call dealloc?
本文介绍了Objective-C中的内存管理基本原则,包括对象的分配、保留计数的增加与减少、自动释放池的工作原理等,并探讨了局部变量及成员变量的管理方式。
1039

被折叠的 条评论
为什么被折叠?



