OC中可以使用“点语法”来简化对getters和setters的调用,下面看代码。
//
// Game.h
// 03_Getters&&Setters
//
// Created by apple on 14-11-8.
// Copyright (c) 2014年 cc. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
* 游戏实体类
*/
@interface Game : NSObject {
//关卡
int _customs;
}
- (void)setCustoms:(int)customs;
- (int)customs;
@end
//
// Game.m
// 03_Getters&&Setters
//
// Created by apple on 14-11-8.
// Copyright (c) 2014年 cc. All rights reserved.
//
#import "Game.h"
@implementation Game
- (void)setCustoms:(int)customs {
NSLog(@"调用setCustoms");
_customs = customs;
}
- (int)customs {
NSLog(@"调用getCustoms");
return _customs;
}
@end
//
// main.m
// 03_Getters&&Setters
//
// Created by apple on 14-11-8.
// Copyright (c) 2014年 cc. All rights reserved.
//
#import <Foundation/Foundation.h>
#include "Game.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Game* pGame = [[Game alloc] init];
//OC可以像Java和C#那样使用 . 来调用方法
//但是语义有区别
//OC中通过.调用方法是寻找相应的getters和setters,并不是直接访问成员变量(没有破坏封装性,只是简化了语法)
//编译器根据上下文环境判断是调用getters和setters,如果是读操作则调用getters如果是写则调用setters
//编译器会把 pGame.customs 转换为 [pGame setCustoms:10]
pGame.customs = 10;
//编译器会把 pGame.customs 转换为 [pGame customs]
NSLog(@"关卡:%d", pGame.customs);
}
return 0;
}
可以通过控制台打印的信息看到的确通过 .调用了getters和setters