#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (nonatomic, retain)NSString * studentName;
@property (nonatomic, retain)NSString * studentID;
@property (nonatomic, assign)int studentAge;
- (id)initWithName:(NSString *)name withID:(NSString *)id withAge:(int)age;
//便利构造器
+ (id)studentWithName:(NSString *)name withID:(NSString *)id withAge:(int)age;
@end
#import "Student.h"
@implementation Student
//自定义构造方法
- (id)initWithName:(NSString *)name withID:(NSString *)id withAge:(int)age
{
if(self = [super init])
{
self.studentName = name;
self.studentID = id;
self.studentAge = age;
}
return self;
}
//便利构造器(快速构造器) 开头字母要与类名相同,开头字母要小写
+ (id)studentWithName:(NSString *)name withID:(NSString *)id withAge:(int)age
{
Student * stu = [[[Student alloc] initWithName:name withID:id withAge:age] autorelease];
return stu;
}
@end
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, char *argv[])
{
@autoreleasepool {
Student * stu1 = [[[Student alloc]initWithName:@"jack"withID:@"2014001" withAge:15] autorelease];
NSLog(@"name = %@, id = %@, age = %d", stu1.studentName, stu1.studentID, stu1.studentAge);
//便利构造器
Student * stu2 = [Student studentWithName:@"lily"withID:@"2014016" withAge:15];
NSLog(@"name = %@, id = %@, age = %d", stu2.studentName, stu2.studentID, stu2.studentAge);
}
return 0;
}