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

我在作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 <Foundation/Foundation.h>
#import "test.h"
#include <stdio.h>

@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://www.cocoachina.com/bbs/read.php?tid-8008.html
相关文章
相关标签/搜索