Objective-C 使用点语法调用getters和setters

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值