大白话解析Objective-C(二):点语法
来源:互联网 发布:appmakr软件使用教程 编辑:程序博客网 时间:2024/06/05 21:11
//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(二):点语法
- 大白话解析Objective-C(三):构造方法+description方法
- Objective-C点语法
- objective-c 点语法
- 【Objective-C】点语法
- Objective-C 【点语法】
- Objective-C 点语法
- Objective-C点语法
- Objective-c - 点语法
- Objective-C ---点语法 (梳理整理)
- 大白话解析Objective-C(一):入门 (Hello World + 第一个类)
- 【Objective-C】06-点语法
- 【Objective-C】06-点语法
- 【Objective-C】06-点语法
- Objective-C - 点语法本质
- objective-c 语法 细节(二)
- Objective-C基础语法(二)
- Objective-C 语法二(对象初始化)
- MapReduce的工作原理
- hdu 1677 Nested Dolls【贪心解嵌套娃娃问题】
- 黑马程序员----构造函数
- 黑马程序员 <梦想之旅十> 银行业务调度系统
- android开发学习——注册时发送激活码
- 大白话解析Objective-C(二):点语法
- XP MSTSC连接WIN7或WIN8问题
- hibernate的findByExample
- linux知识汇总
- 一直想去掉editplus中的BOM头
- 互联网项目如何选取合适的文档及流程
- TIME_WAIT是什么?
- 屌丝创业从理性“认识你自己”开始
- Android ToggleButton Example--开关按钮