您的位置:首页 > 移动开发 > Objective-C

在objective-C类中声明一个数组型成员变量的property

2014-01-13 02:21 495 查看
我在做OpenGL的一个小测试程序时碰到需要定义数组的情况,然后就在一个objc类中定义了一个数组,不过后面问题来了,我该如何为它声明property呢?请见下列示例代码:

//test.h

@interface MyTest : NSObject {

int myArray[5];

}

@end

如果采用

@property int myArray[5];

肯定会出错。
因为@property的声明指示编译器默认地给myArray添加了myArray以及setMyArray的这样一对getter和setter方法。由于objective-C中方法的返回类型不能是数组,所以上述声明property的方式是通不过编译的。
正确的方式是:


//test.h

@interface MyTest : NSObject {

int myArray[5];

}

- (void)outPutValues;

@property int* myArray;

@end

即,使用指针来表示返回类型并作为参数设置类型。

不过这样一来就无法在.m文件的实现中使用@synthesize,而是需要显式地实现这对方法

#import

#import "test.h"

#include

@implementation MyTest

- (int*)myArray

{

return myArray;

}

- (void)setMyArray:(int*)anArray

{

if(anArray != NULL)

{

for(int i=0; i<5; i++)

myArray[i] = anArray[i];

}

}

- (void)outPutValues

{

int a[5];

for(int i=0; i<5; i++)

printf("%d ", (myArray)[i]);

}

@end

int main (int argc, const char *
argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

// insert code here...

int a[] = { [4] = 100 };

MyTest *myTest = [[MyTest alloc] init];

[myTest setMyArray:a];

NSLog(@"The fifth value is: %d", [myTest myArray][4]);

[myTest outPutValues];

[myTest release];

[pool drain];

return 0;

}

这样一来对于数组型变量成员就无法使用点(.)操作符来抽象掉对setter和getter的调用(使用点操作符访问对象的成员数据非常方便,根据索要访问的数据成员处于左值还是右值而由编译器自动判定调用setter还是getter)。

另外,setMyArray的参数类型可以是const:

- (void)setMyArray:(const int*)anArray

转自 http://blog.sina.com.cn/s/blog_7d35fa1a0101htu9.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐