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

//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;
}


运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值