Objective-C 聲明一個C語言類型的數組和訪問方式@property

來源:互聯網
上載者:User

最近在做程式中需要在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*(指標,指向數組的首地址)



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.