----------------------------------------------------------Student.h----------------------------------------------------------
#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 *)aName withID:(NSString *)aID withAge:(int)aAge;
/// (类方法) 便利构造器(在.m文件里实现的时候同时整合了 alloc 方法和自定义 initWithName 方法)
+(id)studentWithName:(NSString *)aName withID:(NSString *)aID withAge:(int)aAge;
@end
#import "Student.h"
@implementation Student
@synthesize studentName = _studentName;
@synthesize studentID = _studentID;
@synthesize studentAge = _studentAge;
-(id)initWithName:(NSString *)aName withID:(NSString *)aID withAge:(int)aAge
{
if(self = [super init])
{
self.studentName = aName;
self.studentID = aID;
self.studentAge = aAge;
}
return self;
}
//便利构造器 开头字母要与类名相同(只是命名规范,不同也可以),开头字母要小写
+(id)studentWithName:(NSString *)aName withID:(NSString *)aID withAge:(int)aAge
{
Student * pRet = [[Student alloc] initWithName:aName withID:aID withAge:aAge];
return [pRet autorelease];
}
@end
----------------------------------------------------------main.m----------------------------------------------------------
#import <Cocoa/Cocoa.h>
#import "Student.h"
int main(int argc, char *argv[])
{
Student * stu1 = [[Student alloc]initWithName:@"xiaownag" withID:@"9836862"withAge:12];
NSLog(@"name = %@,id = %@ age = %d",stu1.studentName,stu1.studentID,stu1.studentAge);
[stu1 release];
//便利构造器
Student * stu2 = [Student studentWithName:@"jack" withID:@"068909"withAge:34];
NSLog(@"name = %@,id = %@ age = %d",stu2.studentName,stu2.studentID,stu2.studentAge);
return 0;
}