您的位置:首页 > 移动开发 > Objective-C

IOS开发基础Object-C(03)—点语法

2015-10-31 17:27 555 查看
今天我们来介绍一下OC中的点语法,官方为了让更多的程序员更加容易的学习开发OC语言,所以增加了一个点语法。在上一篇博客中,我们详细介绍了在OC中类的创建。今天我们就来简单的复习一下:

一、创建一个学生类

1.在Student.h文件中声明

#import< Fountation/Fountation.h>
@interface Student :NSObject{
int  _age;//约定俗成的成员变量以下划线开头,_age
}

-(int)age;//get 方法
-(void)setAge:(int)age;//set方法

@end


2.在Student.m文件中实现

#import"Student.h"//导入头文件
@implementation Student //实现一个类
-(void)setAge:(int)age{
_age=age; //_age是成员变量
}
-(int)age{
return _age;
}
@end


3.main.m文件中调用

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

int main(int argc,const char *argv[])
{
@autoreleasepool{
Student *stu=[[Student alloc] init];//创建对象

[stu setAge:10]; //调用set方法
int age=[stu age]; //调用get方法
NSLog(@"Age is %i",age);

[stu release];//释放对象
}
return 0;
}


二、点语法描述

到这里,我们的一个类就创建好了,下面我们就开始讲点语法。

1.调用set方法

stu.age=10;


2.调用get方法

int age=stu.age;


有人就会有疑问了,stu.age到底调用的是对象还是方法?如果是方法的话那是get方法还是set方法?

这就是OC中点语法和Java中点语法不同的地方了。

3.在Java中,

Student stu=new Student();
stu.age=10;


指的是给Student中的age对象赋值为10.

4.在OC中,stu.age 就是调用的get或set方法了。至于调用的是set方法还是get方法,取决于它是取值还是赋值。也就是说,如果他在等号左边,那就是调用set方法,如果是在等号右边,那就是调用get方法。

用点语法重新写上边的程序就是

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

int main(int argc,const char *argv[])
{
@autoreleasepool{
Student *stu=[[Student alloc] init];//创建对象

stu.age=10;//调用set方法,等价于[stu setAge:10];

int age=stu.age;//调用get方法,等价于int age=[stu age];

NSLog(@"Age is %i",age);

[stu release];//释放对象
}
return 0;
}


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

5.如果你想验证点语法是不是方法调用的话,有很多方法。比如你可以在Student.m的set方法和get方法内部用NSLog加一些打印信息,如果程序运行后有输出打印信息,说明的确是调用了get方法或者set方法

#import"Student.h"//导入头文件
@implementation Student //实现一个类
-(void)setAge:(int)age{
_age=age; //_age是成员变量
NSLog(@"调用了set方法");
}
-(int)age{
NSLog(@"调用了get方法");
return _age;
}
@end


三、self和点语法

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

public void setAge(int newAge) {
this.age = newAge;//将newAge参数的值,赋值给方法调用者的成员变量age

}


2.OC中有个self关键字,作用跟this关键字类似。我这么说完,可能有人就会想这样写OC的set方法了:

- (void)setAge:(int)newAge {
self.age = newAge;
}


3.第2行中的self代表着当前调用setAge:方法的对象。但是第2行代码是绝对错误的,会造成死循环。因为我在前面已经说过了,OC点语法的本质是方法调用,所以上面的代码相当于:

- (void)setAge:(int)newAge {
[self setAge:newAge];
}


很明显,会造成死循环,无限调用setAge:方法,程序就这样崩溃了

四、留在最后的思考

1.在以下代码中,set方法和get方法的方法名是什么?

2.为什么约定俗称成员变量约定俗成使用_age?

代码:

#import< Fountation/Fountation.h>
@interface Student :NSObject{
int  _age;//约定俗成的成员变量以下划线开头,_age
}

-(int)age;//get 方法
-(void)setAge:(int)age;//set方法
-(void)setAge:(int)age andNo:(int)no;
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息