本文介绍了Cocoa结构体和NSMutableArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个NSMutableArray,我试图存储和访问一些结构。我如何做到这一点? 'addObject'给我一个错误,说addObject的参数1的不兼容类型。这里是一个例子('in'是NSFileHandle,'array'是NSMutableArray):
I have an NSMutableArray that I'm trying to store and access some structs. How do I do this? 'addObject' gives me an error saying "Incompatible type for argument 1 of addObject". Here is an example ('in' is a NSFileHandle, 'array' is the NSMutableArray):
//Write points
for(int i=0; i<5; i++) {
struct Point p;
buff = [in readDataOfLength:1];
[buff getBytes:&(p.x) length:sizeof(p.x)];
[array addObject:p];
}
//Read points
for(int i=0; i<5; i++) {
struct Point p = [array objectAtIndex:i];
NSLog(@"%i", p.x);
}
推荐答案
$ c> NSValue 可以使用或:
As mentioned, NSValue
can wrap a plain struct using +value:withObjCType:
or -initWithBytes:objCType:
:
// add:
[array addObject:[NSValue value:&p withObjCType:@encode(struct Point)]];
// extract:
struct Point p;
[[array objectAtIndex:i] getValue:&p];
请参阅。
这篇关于Cocoa结构体和NSMutableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!