iBokan_OC 便利构造器

----------------------------------------------------------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

----------------------------------------------------------Student.m ----------------------------------------------------------

#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 allocinitWithName: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;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值