04点语法

来源:互联网 发布:网络流行语言大全 编辑:程序博客网 时间:2024/06/18 14:11
在Java中,我们可以通过”对象名.成员变量名“来访问对象的公共成员变量,这个就称为”点语法“。
比如:
  在Student类中定义一个公共成员变量age

public class Student{
 int age;
}

public class Test {

  public static void main(String[] args){
    
     Student stu = new Student();
     stu.age = 10;
  }
}

当然,正规的做法是让成员变量私有化,让外界使用公共的get方法和set方法访问成员变量

很多高级语言整都有这种点语法,为了让其他行业的程序员快速上手OC,OC中也引入了点语法,只不过它的含义跟Java不太一样

传统的get方法和set方法

  在正式学习OC的点语法之前,先来看一下传统的get方法和set方法。定义一个Student类,拥有一个成员变量age和对应的get\set方法。

1.Student.h

#import <Foundation/Foundation.h>
@interface Student : NSObject 
{
  int age;
}
- (void)setAge:(int)newAge;
-(int)age;
@end

2.Student.m

#import "Student.h"
@implementation Student
  -(void)setAge:(int)newAge{
   age = newAge;
 }
 -(int)age{
  return age;
 }
@end

3.main.m

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

int main(int argc,const char *argv[]){
  @autoreleasepool{
     Student *stu = [[Student alloc] init];
     [stu setAge:10];
     int age = [stu age];
    NSLog(@"age is %i", age);
   [stu release];
  }
 return 0;
}

使用点语法代替传统的get方法和set方法

前面main.m中main函数的代码可以改为:
int main(int argc,const char *argv[]){
  @autoreleasepool{
   Student *stu = [ [Student alloc] init];
   stu.age = 10; //等价于[stu setAge:10];
   int age = stu.age; //等价于 int age = [stu age];
    NSLog(@"age is %i", age);
    [stu release];
  }
  return 0;
}
把原来的[stu setAge:10]替换成了stu.age = 10。听清楚了,这两种写法是完全等价的。即这里的stu.age 并不是代表直接访问stu对象的成员变量age,而是编译器遇到stu.age = 10 的时候会自动将代码展开成[stu setAge:10];

再说,如果直接访问成员变量的话,OC中应该是这样的语法 stu->age,而不是stu.age

把原来的int age = [stu age]替换成了int age = stu.age。这两种写法又是完全等价的,stu.age并不是直接访问stu对象的成员变量age,而是编译器遇到int age = stu.age的时候会自动将代码展开成int age = [stu age]


点语法和self的陷阱

在Java中,this关键字代表着方法调用者,也就是说,谁调用了这个方法,this就代表谁。所以一般会这样写set方法:
public void setAge(int newAge){
 this.age = age;
}
oc中有个self关键字,作用跟this关键字类似。这么说完,可能有人就会想这样写oc的set方法
-(void)setAge:(int)newAge{
  self.age = newAge;
}
这里的self代表者当前调用setAge:方法的对象。这样就会造成死循环。因为OC点语法的本质是方法调用,所以上面代码相当于:
-(void)setAge:(int)newAge{
 [self setAge:newAge];
}

一点小建议

 如果是第一次接触oc点语法,你可能会真的以为stu.age的意思是直接访问stu对象的成员变量age.其实,有一部分原因是因为我在这里定义的Student类的成员变量名就叫做age,为了更好地区分点语法和成员变量访问,一般我们定义的成员变量会以下划线_开头。比如叫做_age.
1.Student.h
#import <Foundation/Foundation.h>
@interface Student : NSObject{
 int _age;
}
-(void)setAge:(int)newAge;
-(int)age;
@end

2.Student.m
#import "Student.h"
@implementation Student
-(void)setAge:(int)newAge{
  _age = newAge;
}
-(int)age{
 return _age;
}
@end
0 0
原创粉丝点击