大白话解析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(三):构造方法+description方法
- 大白话解析Objective-C(一):入门 (Hello World + 第一个类)
- Objective-C开发——最简单的Objective-C程序与基础语法解析
- objective-c基础语法学习之--(7)拷贝对象
- Objective-C语法之NSString字符串的那些事儿(三)
- FreeMarker语法解析
- merge 语法解析
- Objective-C 【点语法】
- crawler_解析之_jquery_语法选择器使用方法
- Objective-C 语法之集合对象
- Objective-C语法快速参考
- Objective-C 语法之集合对象
- Objective-C语法快速参考
- Objective-C Runtime 解析(三)—— swizzle method
- hive QL 插入语法解析
- Objective-c中使用字面量语法
- Objective-C语法之KVO的使用
- 白话ASP.NET MVC之三:Controller是如何解析出来的
- Objective-C语法之代码块(block)的使用
- recovery下的init.rc语法解析