Nice programing

Objective-C에서 정수 배열 만들기

nicepro 2020. 12. 12. 12:26
반응형

Objective-C에서 정수 배열 만들기


Objective-C에서 정수 배열의 속성을 만드는 데 문제가 있습니다. Obj-C에서 이것이 가능한지 확실하지 않으므로 누군가가 올바르게 수행하는 방법을 찾거나 대체 솔루션을 제공하는 데 도움을 줄 수 있기를 바랍니다.

myclass.h

@interface myClass : NSObject {

@private int doubleDigits[10];
}

@property int doubleDigits;
@end

myclass.m

@implementation myClass

    @synthesize doubleDigits;
    -(id) init {

        self = [super init];

        int doubleDigits[10] = {1,2,3,4,5,6,7,8,9,10};

        return self;
    }

    @end

빌드하고 실행할 때 다음 오류가 발생합니다.

오류 : 'doubleDigits'속성 유형이 ivar 'doubleDigits'유형과 일치하지 않습니다.


이것은 작동합니다.

@interface MyClass
{
    int _doubleDigits[10]; 
}

@property(readonly) int *doubleDigits;

@end

@implementation MyClass

- (int *)doubleDigits
{
    return _doubleDigits;
}

@end

C 배열은 속성에 대해 지원되는 데이터 유형 중 하나가 아닙니다. 선언 된 속성 페이지에서 Xcode 문서의 "The Objective-C 프로그래밍 언어"를 참조하십시오.

지원되는 유형

Objective-C 클래스, Core Foundation 데이터 유형 또는 "Plain Old Data"(POD) 유형에 대한 속성을 선언 할 수 있습니다 (C ++ 언어 참고 : POD 유형 참조). 그러나 Core Foundation 유형 사용에 대한 제약은 "Core Foundation"을 참조하십시오.

POD는 C 어레이를 포함하지 않습니다. 참조 http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html를

배열이 필요한 경우 NSArray 또는 NSData를 사용해야합니다.

해결 방법은 유형 검사를 우회하기 위해 (void *)를 사용하는 것과 같습니다. 할 수는 있지만 코드를 유지 관리하기 어렵게 만듭니다.


lucius가 말했듯이 C 배열 속성을 가질 수 없습니다. an을 사용하는 NSArray것이 방법입니다. 배열은 객체 만 저장하므로 NSNumbers를 사용하여 int를 저장해야합니다. 새로운 리터럴 구문을 사용하면 초기화가 매우 쉽고 간단합니다.

NSArray *doubleDigits = @[ @1, @2, @3, @4, @5, @6, @7, @8, @9, @10 ];

또는:

NSMutableArray *doubleDigits = [NSMutableArray array];

for (int n = 1; n <= 10; n++)
    [doubleDigits addObject:@(n)];

더 많은 정보 : NSArray Class Reference , NSNumber Class Reference , Literal Syntax


나는 단지 추측하고 있습니다.

ivars에 정의 된 변수가 객체에 바로 공간을 할당한다고 생각합니다. 이렇게하면 값으로 배열을 함수에 제공 할 수없고 포인터를 통해서만 제공 할 수 있으므로 접근자를 만들 수 없습니다. 따라서 ivar에서 포인터를 사용해야합니다.

int *doubleDigits;

그런 다음 init-method에서 공간을 할당하십시오.

@synthesize doubleDigits;

- (id)init {
    if (self = [super init]) {
        doubleDigits = malloc(sizeof(int) * 10);
        /*
         * This works, but is dangerous (forbidden) because bufferDoubleDigits
         * gets deleted at the end of -(id)init because it's on the stack:
         * int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
         * [self setDoubleDigits:bufferDoubleDigits];
         *
         * If you want to be on the safe side use memcpy() (needs #include <string.h>)
         * doubleDigits = malloc(sizeof(int) * 10);
         * int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
         * memcpy(doubleDigits, bufferDoubleDigits, sizeof(int) * 10);
         */
    }
    return self;
}

- (void)dealloc {
    free(doubleDigits);
    [super dealloc];
}

이 경우 인터페이스는 다음과 같습니다.

@interface MyClass : NSObject {
    int *doubleDigits;
}
@property int *doubleDigits;

편집하다:

이 작업을 수행 할 수 있는지 확실하지 않습니다. 이러한 값이 실제로 스택에 있는지 아니면 다른 곳에 저장되어 있습니까? 아마도 스택에 저장되어 있으므로이 컨텍스트에서 사용하기에 안전하지 않습니다. ( 초기화 목록에 대한 질문 참조 )

int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
[self setDoubleDigits:bufferDoubleDigits];

이것은 작동합니다

@interface RGBComponents : NSObject {

    float components[8];

}

@property(readonly) float * components;

- (float *) components {
    return components;
}

You can put this in your .h file for your class and define it as property, in XCode 7:

@property int  (*stuffILike) [10];

I found all the previous answers too much complicated. I had the need to store an array of some ints as a property, and found the ObjC requirement of using a NSArray an unneeded complication of my software.

So I used this:

typedef struct my10ints {
    int arr[10];
} my10ints;

@interface myClasss : NSObject

@property my10ints doubleDigits;

@end

This compiles cleanly using Xcode 6.2.

My intention was to use it like this:

myClass obj;
obj.doubleDigits.arr[0] = 4;

HOWEVER, this does not work. This is what it produces:

int i = 4;
myClass obj;
obj.doubleDigits.arr[0] = i;
i = obj.doubleDigits.arr[0];
// i is now 0 !!!

The only way to use this correctly is:

int i = 4;
myClass obj;
my10ints ints;
ints = obj.doubleDigits;
ints.arr[0] = i;
obj.doubleDigits = ints;
i = obj.doubleDigits.arr[0];
// i is now 4

and so, defeats completely my point (avoiding the complication of using a NSArray).

참고URL : https://stackoverflow.com/questions/476843/create-an-array-of-integers-property-in-objective-c

반응형