zoukankan      html  css  js  c++  java
  • 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类的实现文件中)

     

  • 相关阅读:
    leetcode Move Zeroes
    leetcode Same Tree
    leetcode range sum query
    leetcode Invert Binary Tree
    leetcode【sql】 Delete Duplicate Emails
    mac编译PHP报错 configure: error: Please reinstall the libcurl distribution
    Linux添加系统环境变量的两种方法
    Mysql获取去重后的总数
    MySQL查询order by相减select相减的Sql语句
    修改maven本地仓库路径
  • 原文地址:https://www.cnblogs.com/zhangdashao/p/4450137.html
Copyright © 2011-2022 走看看