Objective-C declares an array and access method of C language @ Property

Source: Internet
Author: User
 

Recently, in the program, you need to declare a one-dimensional array in the C language in the objective-C class:

@interface CArrayTest : NSObject{@private    BOOL testArray[4];    }@end

Declare attributes

@property(nonatomic,assign)BOOL testArray[4];


Will promptError: Property can not have array or function type boll [4]

========================================================== ====================================

Correct practice: do not declare the property attribute, that is, do not use the system's set get method, manually add the set and get Methods

#import <Foundation/Foundation.h>@interface CArrayTest : NSObject{@private    BOOL testArray[4];    }- (void)setTestArray:(BOOL*)aTestArray;- (BOOL *)testArray;@end

Implementation in 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

Test code:

// Test code: carraytest * test = [[carraytest alloc] init]; bool TMP [4] = {yes, no, yes, yes}; test. testarray = TMP; // or [test settestarray: TMP]; // output for (INT I = 0; I <4; ++ I) {If (Yes = test. testarray [I]) // or [test testarray] [I]; nslog (@ "yes"); else nslog (@ "no ");}

It is worth noting that:

In objective-C, the returned type cannot be an array of C language. Of course, the array name in C language is actually a corresponding type pointer pointing to the first address of the array,

So we use an array of the bool type, but the parameters and return values in the set and get methods must be bool * (pointer, pointing to the first address of the array)



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.