oc 工廠方法

經過上例看oc建立實例有點麻煩,oc裏面能夠建立工廠方法可讓這個操做更簡單一些(其實就是c#或者java裏面的靜態方法)。java

新建一個「Cocoa Touch Class」文件,命名爲Peoplec#

People.h 寫入spa

@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寫入code

@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

主程序:blog

#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]);
}
相關文章
相關標籤/搜索