您的位置:首页 > 其它

课堂笔记03

2015-07-27 10:07 253 查看

课堂笔记03

这一节将自定义初始化方法

//

// main.m

// OC_03

//

// Created by Ibokan on 15/7/24.

// Copyright (c) 2015年 Law. All rights reserved.

//

#import <Foundation/Foundation.h>
#import "Student.h"


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

@autoreleasepool {

Student *st1 = [[Student alloc] init];
NSLog(@"st的地址为%p",st1);
//st1.sID = 2013;
st1.name = @"大头";
st1.age = 23;

Student *st2 = [[Student alloc] initWithID:@"2013306" SexChoice:@"女"];
st2.name = @"小头";
st2.age = 25;
}
return 0;


}

//

// Student.h

// OC_03

//

// Created by Ibokan on 15/7/24.

// Copyright (c) 2015年 Law. All rights reserved.

//

#import <Foundation/Foundation.h>


@interface Student : NSObject

{

// @public

// NSString *_hero;

// NSString *_name;

// NSString *_name2;

NSString *_sexChoice;


}

//-(void)move;

@property (readonly,nonatomic,retain)NSString *sID;

@property (nonatomic,retain)NSString *name;

@property (nonatomic,assign)NSInteger age;

//自定义初始化方法

/*

initWith//固定写法

*/

-(id)initWithID:(NSString )sID SexChoice:(NSString )sexChoice;

@end

//

// Student.m

// OC_03

//

// Created by Ibokan on 15/7/24.

// Copyright (c) 2015年 Law. All rights reserved.

//

#import "Student.h"


@implementation Student

/*

self:表示指向当前实例对象的指针;

super:表示指向父类对象的指针;

super init:调用父类的init指针;

*/

-(id)init{

self = [super init];

NSLog(@”self的地址为%p”,self);

if (self) {

_sID = @”2013306”;

_sexChoice = @”女”;

}

return self;

}//若没写,系统默认写了,若写了,系统调用该方法

-(id)initWithID:(NSString )sID SexChoice:(NSString )sexChoice{

if (self = [super init]) {

_sID = sID;

_sexChoice = sexChoice;

}

return self;

}

-(void)setAge:(NSInteger)age{

if (age < 0) {

_age = 18;

}

else {

_age = age;

}

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: