zendevelop

learn & share

Objective-C Memory Management

Objective-C Memory Management

Using Reference Counting

每一个从NSObject派生的对象都继承了对应的内存管理的行为。这些类的内部存在一个称为retain count的计数器。使用对应的调用,这个计数器会做自增或者自减。Objective-C runtime知道这个计数器何时变为0,此时会做deallocated。当对应deallocated时,它所占用的所有memory都会被释放。
有三种方法可以让retain count增加:

  • 当你使用含有"alloc","create"的api来创建对象时,这个对象的retain count为1;
  • 另外,当你通过一个包含"copy"的方法来得到一个对象时,这个对象的retain count为1;
  • 你可以通过手动调用"retain"方法来增加retain count;
    当你要减小retain count时,你需要调用release
    A standard allocation of an object

    Bar foo = [ [ Bar alloc ] init ]; Retaining an object*

    Bar* foo = [ [ Bar alloc ] init ]; [ foo retain ];

Using autorelease

Returning an autoreleased object

-( Foo* )getFoo {
    Foo* foo = [ [ Foo alloc ] init ];
    //do something with foo here...
    return [ [ foo autorelease ] ];
}  

The alloc/autorelease pattern

-( void )someMethod {
    Foo* foo = [ [ Foo alloc ] init ] autorelease ];

    //foo is still vaild here,
    //it won't be released until the method exists
    [ foo doSomething ];
}  

Using factory methods versus the traditional allocation pattern

-( void )usingFactories {
    NSMutableArray* array = [ NSMutableArray array ];    //nice, simple, autoreleased.
    NsMutableArray* array2 = [ [ NSMutableArray alloc ] init ];
    // do stuff with array and array2...

    // need to release this one.
    [ array2 release ];

    // [ array release ]; no need to release this,
    // it's already autoreleased
    // if you release it here, it will cause a crash
}  

Creating your own autorelease pool

-( void )inflateMemoryUsage {
    for( NSUInteger n = 0; n < 100000; ++n ) {
        NSAutoreleasePool *pool = [ [ NSAutoreleasePool alloc ] init ];
        //this object is autoreleased
        NSdata* data = [ self getBigBlobofData ];
        // do something with data...
        [ self doStuff:data ];
        [ pool release ];    // the autoreleased objects are deallocated here.
    }
    //nothing left over
}  

posted on 2013-09-24 16:30  zendevelop  阅读(296)  评论(0编辑  收藏  举报

导航