1

重複の可能性:
c-struct を NSArray に配置する最良の方法は何ですか?

NSMutableArray 内で構造体を使用するにはどうすればよいですか?

4

1 に答える 1

2

できません。Foundation のすべてのコレクションは、Objective-C オブジェクトのみを格納できます。astructは Objective-C オブジェクトではないため、そこに格納することはできません。

structただし、単純なNSObjectサブクラスにラップして、それを配列に格納できます。

またはNSValue

#import <Foundation/Foundation.h>

struct TestStruct {
    int a;
    float b;
};

...

NSMutableArray *theArray = [NSMutableArray new];    

...

struct TestStruct *testStructIn = malloc(sizeof(struct TestStruct));
testStructIn->a = 10;
testStructIn->b = 3.14159;

NSValue *value = [NSValue valueWithBytes:testStructIn objCType:@encode(struct TestStruct)];
[theArray addObject:value];

free(testStructIn);

...

struct TestStruct testStructOut;
NSValue *value = [theArray objectAtIndex:0];
[value getValue:&testStructOut];

NSLog(@"a = %i, b = %.5f", testStructOut.a, testStructOut.b);

ちなみに、1 つの構造体にヒープが割り当てられ、1 つのスタックが割り当てられる理由はありません。それが機能していることを示すためにそれをやろうと思っただけです。

于 2013-01-28T18:57:48.840 に答える