很多高级语言都有点语法,能使这种语言方便上手快,oc和java中也都有点语法,但他们的含义不太一样。
写一个java点语法的demo
public class Student{
public int age;
}
public class Test{
public static void main(String [] args){
Student stu = new Student();
stu.age = 10;
}
}
在Student类中定义了一个公共的成员变量age,然后在Test中通过点语法直接给stu的成员变量age赋值。
写一个 oc 点语法的demo
#import <Foundation/Foundtion.h>
@interface Student : NSObject
@property (nonatomic,assign) int age;
(@property相当于系统给自动生成了一个_age变量,并且生成了set和get方法)
- (void)setAge : (int)newAge{
age = newAge;
}
- (int)age{
return age;
}
#import <Foundation/Foundation.h>
#import "Student.h"
int main (int args ,const char *argv []){
@autoreleasepool {
Student *stu = [[Student alloc] init];
stu.age = 10;
NSLog(@"age is %i",stu.age);
}
return 0;
}
oc 的点语法stu.age=10 并不是直接给age赋值,而是一个方法的调用,可以转化成[stu setAge:10];
stu.age 取值可以转化成[stu age];
oc 如果直接访问stu对象的成员变量 age, stu-> age
因此oc的点语法和java是完全不一样的,oc点语法的本质是方法调用,java点语法的本质是直接访问
成员变量。