OC学习那点事:构造方法和description方法
2013-07-21 10:33
232 查看
1.自定义的构造方法
Student.m文件:
Student.h文件:
2.重写父类的description方法
description方法:当使用%@打印一个对象的时候,会调用这个方法
在student.m文件中,重写description方法:
在main.m的main函数中测试:
2013-07-19 00:02:19.410 构造方法[2446:303] age is 15 and no is 2
Student.m文件:
@interface Student : NSObject { int _age; int _no; } ... …(getter/setter) //自己写一个构造方法 -(id)initWithAge:(int)age AndNo:(int)no; @end
Student.h文件:
#import "Student.h" @implementation Student ... …(getter/setter) -(id)initWithAge:(int)age AndNo:(int)no { //首先调用super的构造方法,然后判断self是否为nil if (self = [super init]) { self.age = age; self.no = no; } return self; }main.m文件:
#import <Foundation/Foundation.h> #import "Student.h" int main(int argc, const char * argv[]) { @autoreleasepool { Student *student = [[Student alloc]initWithAge:15 AndNo:2]; NSLog(@"age is %i and no is %i",student.age,student.no); [student release]; } return 0; }
2.重写父类的description方法
description方法:当使用%@打印一个对象的时候,会调用这个方法
在student.m文件中,重写description方法:
-(NSString *)description { NSString *str = [NSString stringWithFormat:@"age is %i and no %i",_age,_no]; return str; }
在main.m的main函数中测试:
Student *student = [[Student alloc]initWithAge:15 AndNo:2]; NSLog(@"%@",student); [student release];输出:
2013-07-19 00:02:19.410 构造方法[2446:303] age is 15 and no is 2
相关文章推荐
- OC基础语法学习4:自定义构造方法和description方法
- OC语言学习 (六) 继承、多态,构造方法,description方法
- 黑马程序员——OC语言学习——关键字id、构造方法、Category-分类、类的本质、 description方法、 SEL方法
- OC核心语法之构造方法、Category分类、类的本质、description和SEL
- oc中的构造方法和description方法,变量的作用呀
- oc中的构造方法和description方法,变量的作用域,
- OC学习---description方法重写
- 黑马程序员_OC构造方法和ID类型学习学习
- 黑马程序员——OC学习——@property和构造方法
- OC_构造方法,自定义构造方法,分类,类的深入研究,description,SEL数据类型笔记
- OC基础语法<1.2> 入门面向对象语法-构造方法和description
- 黑马程序员之ios学习总结——10 OC语言的构造方法和分类
- OC学习2——构造方法和description方法
- OC学习笔记之OC类自定义构造方法
- OC的特有语法-分类Category、 类的本质、description方法、SEL、NSLog输出增强、点语法、变量作用域、@property @synthesize关键字、Id、OC语言构造方法
- 黑马视频学习笔记-OC-id、构造方法
- 黑马程序员-------OC----构造方法和description方法
- 黑马程序员学习笔记14_OC之构造方法
- 【黑马程序员】-我的OC学习笔记(3)-存取器方法和构造方法重写
- 黑马程序员———OC学习第四天(构造方法及分类)