我有一个 NSMutableArray,我正在尝试存储和访问一些结构。我该怎么做呢? “addObject”给我一个错误,说“addObject 的参数 1 的类型不兼容”。这是一个示例(“in”是 NSFileHandle,“array”是 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);
}
如上所述,NSValue
可以使用包装一个简单的结构+value:withObjCType: http://developer.apple.com/mac/library/documentation/cocoa/Reference/Foundation/Classes/NSValue_Class/Reference/Reference.html#//apple_ref/doc/uid/20000177-value_withObjCType_ or -initWithBytes:objCType: http://developer.apple.com/mac/library/documentation/cocoa/Reference/Foundation/Classes/NSValue_Class/Reference/Reference.html#//apple_ref/doc/uid/20000177-initWithBytes_objCType_:
// add:
[array addObject:[NSValue value:&p withObjCType:@encode(struct Point)]];
// extract:
struct Point p;
[[array objectAtIndex:i] getValue:&p];
See the 数量和价值指南 http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/NumbersandValues/Articles/Values.html#//apple_ref/doc/uid/20000174-BAJJHDEG了解更多示例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)