Objective C 2.0 简明教程 (5) 属性(Property)
Objective C 2.0 简明教程 (5) 属性(Property)
作者:Administrator
周六, 2009年 03月 28日 07:47
Objective C 2.0 为我们提供了property。它大大简化了我们创建数据成员读写函数的过程,更为关键的是它提供了一种更为简洁,易于理解的方式来访问数据成员。
我们先来看一下在Objective C 1.x下我们声明Book类的头文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//
// Book.h
#import <Cocoa/Cocoa.h>
@interface Book : NSObject {
NSString *title;
NSNumber* numofpages;
}
- (id)initWithTitle:(NSString*) booktitle andNumofpages:(NSNumber*) num;
- (NSString*) title;
- (void) setTitle:(NSString*)newtitle;
- (NSNumber*) numofpages;
- (void) setNumofpages:(NSNumber*)newnumofpages;
- (NSString*) summary;
@end
在Objective C 2.0下,我们可以通过声明与数据成员同名的property来省去读写函数的声明。代码如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//
// Book.h
#import <Cocoa/Cocoa.h>
@interface Book : NSObject {
NSString *title;
NSNumber* numofpages;
}
- (id)initWithTitle:(NSString*) booktitle andNumofpages:(NSNumber*) num;
@property (retain) NSString* title;
@property (retain) NSNumber* numofpages;
@property (readonly) NSString* summary;
@end
我们为每一个数据成员声明了一个property。即使Book类中没有summary这个数据成员,我们同样可以声明一个名为summary的property。声明property的语法为:
@property (参数) 类型 名字;
这里的参数主要分为三类:读写属性(readwrite/readonly),setter语意(assign/retain/copy)以及atomicity(nonatomic)。
assign/retain/copy决定了以何种方式对数据成员赋予新值。我们在声明summary propery时使用了readonly,说明客户端只能对该property进行读取。atomicity的默认值是atomic,读取函数为原子操作。
下面我们来看一下在Objective C 1.x 下implementation文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
相关文档:
http://man.lupaworld.com/content/develop/c&c++/c/c.htm
1. 如果参数是指针,且仅作输入用,则应在类型前加const,以防止该指针在函数体内被意外修改
2. 在函数体的“入口处”,对参数的有效性进行检查
在函数体的“出口处”,对return语句的正确性和效率进行检 ......
C/C++ development with the Eclipse Platform
Pawel Leszek
摘要:通过本文你将获得如何在Eclipse平台上开发C/C++项目的总体认识。虽然Eclipse主要被用来开发Java项目,但它的框架使得它很容易实现对其他开发语言的支持。在这篇文章里,你将学会如何使用CDT(C/C++ Development Toolkit),一个在Eclipse平台上最 ......
作者:Kevin Lynx 来源:C++博客
转自:http://www.kuqin.com/language/20080319/4797.html
众多C++书籍都忠告我们C语言宏是万恶之首,但事情总不如我们想象的那么坏,就如同goto一样。宏有
一个很大的作用,就是自动为我们产生代码。如果说模板可以为我们产生各种型别的代码(型别替换),
那么宏其实可以为我们在符号上 ......
问题源于论坛的一道题目:
http://topic.csdn.net/u/20100216/21/ec98464e-a47e-4263-bb1c-a001e130ba87.html
下面是问题:
设int arr[]={6,7,8,9,10};
int *ptr=arr;
*(ptr++)+=123;
printf("%d,%d",*ptr,*(++ptr));
答案为什么是:8,8
问题的焦点也落在printf执行的问题上,到底先执行谁,后执行谁, 还有部分 ......
原帖一:http://blog.csdn.net/dotphoenix/archive/2009/05/20/4203075.aspx
原贴二:http://www.cocoachina.com/bbs/read.php?tid-8008.html
@property (参数) 类型 名字;
这里的参数主要分为三类:读写属性(readwrite/readonly),setter语意(assign/retain/copy)以及atomicity(nonatomic)。
assign/retain/copy ......