我在作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