Objective-C Memory Management
2013-09-24 16:30
363 查看
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 }
相关文章推荐
- iOS Objective C Memory management
- Objective-C MemoryManagement(1)
- Objective-C Memory Management For Lazy People
- Memory Management in Objective-C
- Memory Management in Objective-C Tutorial 读后小记
- Memory Management in Objective-C
- Objective-c using @property and memory management
- objective-C MemoryManagement(2)
- System and device programming-Memory management in Windows
- C#Memory Management for Unity Developers (part 2 of 3)
- mm: iommu: An API to unify IOMMU, CPU and device memory management
- C++ Memory Management std::allocate
- Windows 2000 Page Based Memory Management
- Garbage Collection: Algorithms for Automatic Dynamic Memory Management
- Manage objective c object memory in Block
- Memory management in C programs
- linux-kernel-map,linux-memory-management,Linux-storage-stack三幅很好的图
- 想翻译Memory Management Algorithms and Implementation in c/c++
- iTron3学习笔记(一) System Calls of Memory Pool Management Functions
- Windows Memory Management