您的位置:首页 > 移动开发 > Objective-C

IOS开发基础Object-C( 04)—构造方法和description方法

2015-11-01 11:51 417 查看
在上一篇博客中,我们简单介绍了一下点语法和self,相信大家对点语法以及self有了一点的了解,点语法的本质就是调用get方法和set方法。那么今天我们再来介绍一下构造方法和description。

注:现在我也是在学习阶段,有错误请大家指出,多多包涵,本博客仅属于读书笔记一类。大家也可以关注我的微博@我叫崔某某,让我们共同交流,共同学习

一、构造方法

1、依照惯例我们在Student.h文件中声明一个类Student

#import<Foundation/Foundtion.h>
@interface Student :NSObject{
int _age;
int _no;
}
-(int)age;              //get方法
-(void)setAge:(int)age; //set方法
-(int)no;
-(void)setNo:(int)no;

@end


2、我们在这基础上进行构造方法的声明,构造方法为动态方法,返回id类型(包含所有对象类型),方法名默认以init开头。

#import<Foundation/Foundtion.h>
@interface Student :NSObject{
int _age;
int _no;
}
-(int)age;              //get方法
-(void)setAge:(int)age; //set方法,方法名为:setAge:
-(int)no;
-(void)setNo:(int)no;
//自己写一个构造方法,返回(id)类型,默认init开头

-(id)initWithAge:(int)age andNo:(int)no;

//注意:这里的方法名是initWithAge:andNo:,:也是方法名一部分
@end


3、下面我们就在Student.m文件实现这个方法

#inport"Student.h"
@implementation Student
-(int)age{
return _age;
}
-(void)setAge:(int)age{
_age=age;
}
-(int)no{
return _no;
}
-(void)setNo:(int)no{
_no=no;
}
//构造方法的实现
-(id)initWithAge:(int)age andNo:(int)no{
//首先调用super的构造方法
//self=[super init];将super构造方法放入if中进行判断,如果不为空,进行赋值操作
if(self=[super init])//如果对象不为空
{
//赋值操作
_age=age;  //等同于sel.age=age;
_no=no;    //等同于self.no=no;
}
return self;//返回当前对象
}
@end


4、main.m文件,调用自定义的构造方法

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

int main(int argc,const char *argv[])
{
@autoreleasepool{
Student *stu=[[Student alloc] initWithAge:24 andNo:01];//创建对象,调用自己写的构造方法并赋值

NSLog(@"Age is %i and No is %i",stu.age,stu.no);

[stu release];//释放对象
}
return 0;
}


5、内容补充:

//打印整个对象
NSLog(@"%@",stu);


“%@”代表打印一个OC对象,输出结果为:

2015-11-01 10:56:33.227 构造方法[4432:303] < Student :0x100109950 >。

其中0x100109950为对象的内存地址。

但是有时候我们并不像要这种形式的打印结果,在Java中,打印一个对象的时候会调用toString()方法,那么在OC里则调用description方法。下面我们就来介绍一下description方法。

二、description方法

description方法的作用是打印对象,跟Java里的toString有点类似。对于一个Student类,如果没有重写description方法,NSLog(@“%@”,p),输出的是Student:地址,而我们想要的效果是打印出Student的成员变量,所以我们可以在Student类里重写description方法。description方法,返回值是OC字符串。

1、重写实例方法

NSString的字符串拼接用的是stringWithFormat

//重写父类的description方法
//当使用%@打印一个对象的时候,会调用这个方法
- (NSString *)description{
NSString *str=[NSString stringWithFormat:@"age is %i and no is %i",_age,_no];
return str;
}


三、友情链接

01-OC概述

http://pan.baidu.com/s/1jGuByR0

02-第一个OC类

http://pan.baidu.com/s/1hqCWz7Q

03-点语法

http://pan.baidu.com/s/11DsdC

04-构造方法和description方法

http://pan.baidu.com/s/1hq2MX7m
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息