【语法】构造方法和description

构造方法和description

1.【首先是创建一个student类】

2【那么先是student.h文件】

 

 1 //
 2 //  Student.h
 3 //  pro4
 4 //
 5 //  Created by 裴烨烽 on 14-1-25.
 6 //  Copyright (c) 2014年 裴烨烽. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 @interface Student : NSObject
12 {
13 
14     int _age;
15     int _no;
16 }
17 
18 -(void)setAge:(int)age;
19 -(int)age;
20 
21 -(void)setNo:(int)no;
22 -(int)no;
23 
24 
25 //自己写一个构造方法;
26 -(id)initWithAge:(int)age andNo:(int)no;//这里只是声明
27 
28 
29 @end

 

3.【student.m文件】

 1 //
 2 //  Student.m
 3 //  pro4
 4 //
 5 //  Created by 裴烨烽 on 14-1-25.
 6 //  Copyright (c) 2014年 裴烨烽. All rights reserved.
 7 //
 8 
 9 #import "Student.h"
10 
11 @implementation Student
12 
13 -(void)setAge:(int)age{
14     _age=age;
15 }
16 
17 -(void)setNo:(int)no{
18 
19     _no=no;
20 }
21 
22 -(int)age{
23     return _age;
24 }
25 
26 -(int)no{
27     return _no;
28 }
29 
30 
31 //实现构造方法
32 -(id)initWithAge:(int)age andNo:(int)no{
33 
34 //首先要调用super的构造方法
35     
36    self=[super init];      
37 if(self)                【1】
38 {
39     _age=age;           【2】
40     _no=no;             【3】
41 
42 }
43     
44     //这一句话等同于上面一句
45     //如果self不为nil   这样写严谨    【1】+【2】+【3】=【4】+【5】+【6】
46     if(self!=nil)          【4】
47     {
48         _age=age;          【5】
49         _no=no;            【6】
50     }
51     
52     
53      return self;
54 }
55 
56 
57 //重写父类的description方法
//主要是由来重写输出的格式
58 //当使用%@的打印一个对象的时候,会调用这个方法 59 -(NSString *)description{ 【8】 60 //return @"验证调用了description方法"; 61 62 //打印我想要输出的格式。 63 //"age is 27 and no is 100"; 64 //那么就要使用以下方法 66 NSString *str= [NSString stringWithFormat:@"age is %i and no is %i",_age,_no]; 【9】 67 return str;                                    【10】 68 69 } 70 71 @end

 

【main()】中主要体现了主要知识点:

1.%@是用来输出指针地址。

2.NSLog(@"%@",stu);

这段话会调用student.m中的这短话,description主要作用是预设输出格式。

-(NSString *)description{                        【8
66    NSString *str= [NSString stringWithFormat:@"age is %i and no is %i",_age,_no];     【967     return str;                                             【1068     

(2).

 1 //
 2 //  main.m
 3 //  pro4
 4 //
 5 //  Created by 裴烨烽 on 14-1-25.
 6 //  Copyright (c) 2014年 裴烨烽. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 #import "Student.h"
11 
12 int main(int argc, const char * argv[])
13 {
14 
15     @autoreleasepool {
16         
17         //oc字符串写法
18         char *s="itcast";
19         //OC中的字符串写法
20         NSString *str=@"itcast";
21         
22         
23         
24   Student *stu=[[Student alloc /*静态方法:类的方法是静态*/]/*动态方法*/initWithAge:15 andNo:2]; 25         NSLog(@"age is %i and no is %i",stu.age,stu.no);
26        
27         
28         //java中可以这样调用 system.out.println(stu);同样的,如下:
29         NSLog(@"%@",stu);//<Student: 0x100109a10>   //%@表示要打印一个oc对象打印的是内存地址。   【7】详见返回student.m中的【8】【9】【10】
30 31 } 32 return 0; 33 }

 

posted @ 2014-01-25 22:38  太过于漂流  阅读(449)  评论(0编辑  收藏  举报