点语法

1 int main(int argc, const char * argv[])
2 {
3    @autoreleasepool {
4      Student *stu = [[Student alloc] init];
5
6      // 设置age的值
7      stu.age = 10; // 等价于[stu setAge:10];
8
9      // 取出age的值
10      int age = stu.age; // 等价于int age = [stu age];
11
12      NSLog(@"age is %i", age);
13
14      [stu release];
15    }
16    return 0;
17 }
OC中点语法的含义跟Java是完全不一样的,OC点语法的本质是方法调用,不是直接访问成员变量。

一点小建议:

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

原文地址:https://www.cnblogs.com/tzktzk1/p/3329603.html