读书人

+号级别得成员方法兑现

发布时间: 2012-08-22 09:50:35 作者: rapoo

+号级别得成员方法实现

Demo:加号级别的成员方法的实现:

#import <Foundation/Foundation.h>

@interface Person:NSObject

{

????? int _age;

}

-(id)initWithAge:(int)age;

+(id)personWithAge:(int)age;

-(void)print;

@end

?

@implementation Person

?

-(id)initWithAge:(int)age

{

????? self = [super init];

????? if (nil != self) {

???????? _age = age;

????? }

????? return self;

}

+(id)personWithAge:(int)age

{??? //返回id类型和用到self是为子类考虑,子类继承Person,当调用该方法是返回的是子类的对象

????? //在+级别的方法中,一般用self

????? id obj = [[self alloc] initWithAge:age];

????? return [obj autorelease];

?????

}

-(void)print

{

????? NSLog(@"age = %d",_age );

}

@end

?

@interface Student : Person

@end

?

@implementation Student

@end

?

?

int main (int argc, const char * argv[]) {

??? NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

?????

????? Person* p = [Person personWithAge:20];

????? [p print];

?????

????? Student* stu = [Student personWithAge:30];

????? NSLog(@"%@", NSStringFromClass([stu class]));

????? [stu print];

??

??? [pool drain];

??? return 0;

}

?

读书人网 >移动开发

热点推荐