oc 工厂方法
通过上例看oc创建实例有点麻烦,oc里面可以创建工厂方法可以让这个操作更简单一些(其实就是c#或者java里面的静态方法)。
新建一个“Cocoa Touch Class”文件,命名为People
People.h 写入
@interface People : NSObject{ int _age; NSString* _name; } -(int)getAge; -(NSString*)getName; +(People*)peopleWithAge:(int)age andName:(NSString*)name;//+就是工厂方法,即表示静态方法
-(id)initWidthAge:(int)age andName:(NSString*)name;//id指的是任意类型 @end
People.m写入
@implementation People -(int)getAge{ return _age; } -(NSString*)getName{ return _name; } +(People*)peopleWithAge:(int)age andName:(NSString*)name{ return [[People alloc] initWidthAge:age andName:name]; } - (instancetype)initWidthAge:(int)age andName:(NSString *)name { self = [super init]; if (self) { _age=age; _name=name; } return self; } @end
主程序:
#import <UIKit/UIKit.h> #import "AppDelegate.h" #import "People.h" int main(int argc, char * argv[]) { People *p=[People peopleWithAge:30 andName:@"netcorner"]; NSLog(@"p.age %d,p.name %@",[p getAge], [p getName]); }