Memory issues on iOS development

Memory management

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html%23//apple_ref/doc/uid/10000011i

 

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?

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值