代码改变生活

OC学习 点语法实质 与 变量作用域

其实点语法本质还是方法调用

当使用点语法时,编译器会自动展开成相应的方法

1 #pragma mark - 点语法访问成员变量 点语法的本质就是get和set方法 对象.属性 其实质就是get方法
2     //cat->_age =9; 再成员变量 @public情况下才能访问
3     cat.age = 9; 等于 [cat setAge: 9];//展开后
4  int  ages = cat.age;// 等于 对象的get方法

注意:会引发死循环

 1 - (void)setAge:(int)age
 2 {
 3     //_Age = age;
 4     self.age = age;
 5 }
 6 - (int)age
 7 {
 8    // return _Age;
 9     return self.age;
10 } 

 变量的作用域

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface Person : NSObject
 4 
 5 {
 6     
 7     int _age; //@interface中变量默认是@public
 8     @protected
 9     int _height;   //只能在当前类和子类的对象方法中访问
10     @private
11     int _weight; //只能在当前类的对象方法中才能直接访问
12     @package
13     NSString *_names;//只能在当前框架内使用
14 }
15 
16 - (int) age;
17 - (void) setAge:(int)age;
18 
19 - (int) height;
20 - (void) setHeight:(int)height;
21 
22 - (int) weight;
23 - (void) setWeight:(int)weight;
24 
25 - (NSString *)names;
26 - (void) setName:(NSString *)names;
27 @end
28 
29 
30 
31 @implementation Person
32 
33 {
34     
35     NSString *birthday;//@implementation中变量默认是@private
36     
37 }
38 
39 
40 
41 -(int) age
42 
43 {
44     return -age
45 }
46 
47 -(void) setAge:(int)age
48 
49 {
50     -age=age;
51 }
52 
53 -(int) height
54 
55 {
56     return _height;
57 }
58 
59 -(void) setHeight:(int)height
60 
61 {
62     -height=height;
63 }
64 
65 -(int) weight
66 
67 {
68     return _weight;
69 }
70 
71 -(void) setWeight:(int)weight
72 
73 {
74     _weight=weight;    
75 }
76 
77 -(NSString *)name
78 
79 {
80     return _name;
81 }
82 
83 -(void) setName:(NSString *)name
84 
85 {
86     _name=name;
87 }
88 @end

  1  @public (公开的)在有对象的前提下,任何地方都可以直接访问。

  2  @protected (受保护的)只能在当前类和子类的对象方法中访问

  3  @private (私有的)只能在当前类的对象方法中才能直接访问

  4  @package (框架级别的)作用域介于私有和公开之间,只要处于同一个框架中就可以直接通过变量名问。

 5 xcode 环境中OC默认

@interface中的声明的成员变量默认是public(在.h类的声明文件中)

@implatation中声明的成员变量默认是private(在.m类的实现文件中)

 

posted on 2015-04-23 12:35  张大少。  阅读(185)  评论(0编辑  收藏  举报

导航

繁星纵变 智慧永恒