我试图将GLKVector3对象添加到NSMutableArray中。我知道NSMutableArrays将只接受某些对象,所以对我来说最好的方法也是将GLKVector3添加到数组。
这是代码示例:
for(id basenormal in [jsnmvtx objectForKey:@"baseNormals"]){
[basenormalsVectorArrays addObject:GLKVector3MakeWithArray(basenormal)];
}
谢谢
最佳答案
问题是GLKVector3
是C风格的struct
,而不是对象。因此,它不知道如何响应retain
或release
,因此无法与NSArray
一起使用。
您可以做的是将每个对象包装到NSValue
中,因为这是一种对象类型,并且它知道如何在其中保留任意C类型。它并不是特别整洁,因为您跨越了C和Objective-C之间的边界,但是例如
GLKVector3 someVector;
[array addObject:[NSValue valueWithBytes:&someVector objCType:@encode(GLKVector3)]];
...
GLKVector3 storedVector;
NSValue *value = ... something fetched from array ...;
[value getValue:&storedVector];
// storedVector now has the value of someVector
这会将
someVector
的内容复制到NSValue
中,然后再次将它们复制到storedVector
中。如果您希望在数组中保留对
valueWithPointer:
的引用而不是复制内容,则可以使用pointerValue
和someVector
,尽管那样您将需要注意手动内存管理,因此更好的解决方案可能是使用NSData
:// we'll need the vector to be on the heap, not the stack
GLKVector3 *someVector = (GLKVector3 *)malloc(sizeof(GLKVector3));
[array addObject:[NSData dataWithBytesNoCopy:someVector length:sizeof(GLKVector3) freeWhenDone:YES]];
// now the NSData object is responsible for freeing the vector whenever it ceases
// to exist; you needn't do any further manual management
...
GLKVector3 *storedVector = (GLKVector3 *)[value bytes];
关于iphone - 将GLKVector3添加到NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15032543/