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]);
}
复制代码


相关文章
OC泛型的使用
在声明类的时候,不确定某种属性或方法类型,在使用这个类的时候才确定,就可以采用泛型 如果没有自定义泛型,默认就是id类型
280 0
|
iOS开发
OC中的内省方法(Introspection)
OC中的内省方法(Introspection)
134 0