标签:objective-c 内存管理 ios
// Person.h @interface Person @property(nonatomic, assign) int age; @end
// Person.m #improt <Foundation/Foundation.h> @implementation Person - (void)dealloc() { NSLog(@"Person dealloc"); [super dealloc]; } @end
// main.m #improt <Foundation/Foundation.h> #improt "Person.h" int main() { @autorelease {// 创建了一个自动释放池 Person* person1 = [[[Person alloc] init] autorelease]; person1.age = 25; }// 释放池销毁,这一行之后会打印出:"Person dealloc" // 释放池个数不限 @autorelease { Person* person2 = [[[Person alloc] init] autorelease]; person2.age = 25; // 释放池可以嵌套 @autorelease { Person* person3 = [[[Person alloc] init] autorelease]; person3.age = 25; } } // 另一种创建方式 NSAutoreleasePool* p = [[NSAutoreleasePool alloc] init];// 创建了一个自动释放池 Person* person4 = [[[Person alloc] init] autorelease]; person4.age = 25; [pool release];// 释放池销毁 return 0; }
@autorelease{ // 释放池内对象 }
NSAutoreleasePool* p = [[NSAutoreleasePool alloc] init];// 创建了一个自动释放池 // 释放池内对象 [pool release];
Person* person2 = [[[Person alloc] init] autorelease]; [person2 autorelease];或者
Person* person2 = [[[[Person alloc] init] autorelease] autorelease];
Person* person2 = [[[Person alloc] init] autorelease]; [person2 release];
// Person.h @interface Person @property(nonatomic, assign) int age; + (id)person; + (id)personWithAge:(int)age; @end
// Person.m #improt <Foundation/Foundation.h> @implementation Person // 快速返回一个自动释放的对象 + (id)person { retur [Person alloc] init] autorelease]; } + (id)personWithAge:(int)age { Person* p = [Person alloc] init] autorelease]; p.age = age retur p; } @end
// main.m #improt <Foundation/Foundation.h> #improt "Person.h" int main() { @autorelease{ Person* p1 = [Person person]; p1.age = 22; Person* p1 = [Person personWithAge:25]; // 类似的系统方法 NSString* str = [NSString stringWithFormat("%d to string",2)]; NSNumber* n = [NSNumber numberWithInt:100]; } retur 0; }
// Student.h @interface Student:Person @property(nonatomic, assign) int grade; @end
// Student.m #improt <Foundation/Foundation.h> @implementation Student @end
// main.m #improt <Foundation/Foundation.h> #improt "Person.h" int main() { @autorelease{ Student* s = [Student personWithAge:10]; s.grade = 1;// 报错 } retur 0; }
+ (id)person { // 改为self后返回调用者的实例 retur [self alloc] init] autorelease]; } + (id)personWithAge:(int)age { Person* p = [self alloc] init] autorelease]; // 设置父类(Person)的age值 p.age = age retur p; }
标签:objective-c 内存管理 ios
原文地址:http://blog.csdn.net/xufeng0991/article/details/43302993