//// Person.h#import@interface Person : NSObject@property (nonatomic, assign) int age;+ (instancetype)person;- (instancetype)initWithAge:(int)age;+ (instancetype)personWithAge:(int)age;@end
// Person.m#import "Person.h"@implementation Person//提供构造方法的时候也要提供类工厂方法(API里面是这么写的),如果是MRC还要提供antorelease.+ (instancetype)person //类工厂方法{ return [[[self alloc] init] autorelease];}- (instancetype)initWithAge:(int)age{ //构造方法 if (self = [super init]) { _age = age; } return self;}+ (instancetype)personWithAge:(int)age //类工厂方法{ /* Person *p = [[self alloc] init]; p.age = age; return [p autorelease]; */ return [[[self alloc] initWithAge:age] autorelease]; //self = Person;}- (void)dealloc{ NSLog(@"%s", __func__); [super dealloc];}@end
//// main.m// auatorelease应用场景#import#import "Person.h"int main(int argc, const char * argv[]) { @autoreleasepool { Person *p = [[[Person alloc] init] autorelease]; p.age = 10; NSLog(@"age = %i", p.age); Person *p1 = [[[Person alloc] init] autorelease]; Person *p2 = [[[Person alloc] init] autorelease]; Person *1p = [Person person]; 1p.age = 10; NSLog(@"age = %i", 1p.age); // 注意: Foundation框架的类, 但凡是通过类工厂方法创建的对象都是autorelease的 [[NSString alloc] init]; [NSString string]; // [NSString alloc] initWithString:(NSString *)// [NSString stringWithString:(NSString *)]; Person *p = [[[Person alloc] initWithAge:10] autorelease]; NSLog(@"age = %i", p.age); Person *p = [Person personWithAge:10]; NSLog(@"age = %i", p.age); } return 0;}
本文转自农夫山泉别墅博客园博客,原文链接:http://www.cnblogs.com/yaowen/p/7429029.html,如需转载请自行联系原作者