你的位置:首页 > 软件开发 > 操作系统 > 【Objective

【Objective

发布时间:2016-03-14 16:00:11
在Java中,我们可以通过"对象名.成员变量名"来访问对象的公共成员变量,这个就称为"点语法"。比如:1.在Student类的第2行定义了一个公共的成员变量age1 public class Student {2 public int ...

Java中,我们可以通过"对象名.成员变量名"来访问对象的公共成员变量,这个就称为"点语法"。比如:

1.在Student类的第2行定义了一个公共的成员变量age

1 public class Student {2   public int age;3 }
1 public class Test {2 3   public static void main(String[] args) {4     Student stu = new Student();5     stu.age = 10;6   }7 8 }
【Objective

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

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

 

一、传统的get方法和set方法

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

1.Student.h

【Objective
 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
【Objective

1> 在第5行实现了set方法

2> 在第9行实现了get方法

 

3.main.m

把定义好的Student类放到main函数中使用

【Objective

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

上面演示了OC传统get\set方法的简单用法,接下来使用点语法来代替。

前面main.m中main函数的代码可以改为:

【Objective
 1 #import "Student.h" 2 3 @implementation Student 4 5 - (void)setAge:(int)newAge { 6   NSLog(@"调用了setAge方法"); 7   age = newAge; 8 } 9 10 - (int)age {11   NSLog(@"调用了age方法");12   return age;13 }14 15 @end
【Objective

 

三、点语法和self的陷阱

1.在Java中,this关键字代表着方法调用者,也就是说,谁调用了这个方法,this就代表谁。所以一般会这样写set方法:

1 public void setAge(int newAge) {2   this.age = newAge;3 }
 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
【Objective

2.Student.m,注意第6行和第10行

【Objective

原标题:【Objective

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录