最近在做程式中需要在Objective-C類中聲明一個C語言方式的一維數組:
@interface CArrayTest : NSObject{@private BOOL testArray[4]; }@end
聲明屬性如果是
@property(nonatomic,assign)BOOL testArray[4];
會提示錯誤:Property can not have array or function type BOLL[4]
=======================================================================
正確做法:不聲明property屬性,也就是不用系統的set個get方法,自己手動添加set和get方法
#import <Foundation/Foundation.h>@interface CArrayTest : NSObject{@private BOOL testArray[4]; }- (void)setTestArray:(BOOL*)aTestArray;- (BOOL *)testArray;@end
在CArrayTest.m中的實現
#import "CArrayTest.h"@implementation CArrayTest- (void)setTestArray:(BOOL*)aTestArray{ if(aTestArray != NULL) { for(int i = 0; i < 4; ++i) { testArray[i] = aTestArray[i]; } }}- (BOOL *)testArray{ return testArray;}@end
測試代碼:
//測試代碼CArrayTest *test = [[CArrayTest alloc]init];BOOL tmp[4] = {YES,NO,YES,YES}; test.testArray = tmp; //或者是 [test setTestArray:tmp]; //輸出for(int i = 0; i < 4; ++i){ if(YES == test.testArray[i]) //或者是 [test testArray][i]; NSLog(@"YES "); else NSLog(@"NO ");}
值得注意的是:
Objective-C中傳回型別不能是C語言的數組,當然C語言中數組名其實就是一個對應類型指標,指向數組的首地址,
所以我們是用的BOOL類型的數組,但在set和get方法中的參數和傳回值都必須是BOOL*(指標,指向數組的首地址)