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

大白话解析Objective-C(二):点语法

2013-08-04 22:53 295 查看
//Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject {
int _age;
}

- (void) setAge:(int)age;
- (int) age;

@end


//Student.m

#import "Student.h"

@implementation Student

- (void) setAge:(int) age {
NSLog(@"use setAge method.");
_age = age;
}

- (int) age {
NSLog(@"use age method.");
return _age;
}

@end

//main.m

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

int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

Student *stu = [[Student alloc] init];

//注意:OC的点语法(stu.age)并不是访问成员变量
//其实这很显然,因为我们定义的成员变量是 _age
//OC的点语法实质是编译器在编译时把stu.age替换成相对应的方法

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

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

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

[stu release];

[pool drain];
return 0;
}


运行结果:



第一、二行的输出说明调用了set方法,然后调用了get方法

经典错误:

//Student.m

#import "Student.h"

@implementation Student

- (void) setAge:(int) age {
NSLog(@"use setAge method.");
//_age = age;
self.age = age;     //这样做是错的,因为set方法会无限调用自身造成死循环
}

- (int) age {
NSLog(@"use age method.");
//return _age;
return self.age;    //这样做也是错的,因为get方法会无限调用自身造成死循环
}

@end

错误示例截图:



关于如何访问成员变量:

//Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject {
@public     //公有,允许外界访问,还有私有:@private,保护:@protected
int _age;
}

- (void) setAge:(int)age;
- (int) age;

@end

//main.m

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

int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

Student *stu = [[Student alloc] init];

//由于stu是指针,所以可以通过箭头访问成员变量 _age
stu->_age = 18;
int age = stu->_age;

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

[stu release];

[pool drain];
return 0;
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Objective-C