NSMutableArray 内で構造体を使用するにはどうすればよいですか?
質問する
2349 次
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 に答える