2013-02-22 109 views
1

我尝试添加GLKVector3对象到一个NSMutableArray。我知道NSMutableArrays只会接受某些对象,所以对我来说,最好的方法是将一个GLKVector3添加到数组中。添加GLKVector3到一个NSMutableArray

这里是一个代码示例:

 for(id basenormal in [jsnmvtx objectForKey:@"baseNormals"]){ 
      [basenormalsVectorArrays addObject:GLKVector3MakeWithArray(basenormal)]; 
     } 

感谢

回答

3

问题是GLKVector3是C风格struct,不是对象。所以它不知道如何应对retainrelease回应,因此不会有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 

那将copythe的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]; 
+0

感谢您的回复。 Objective-C的指针,以“浮动*”的隐式转换是不允许用圆弧 – samb90 2013-02-22 21:21:17

+0

在这是否发生什么行:现在不知道如何纠正它,我得到这个错误? – Tommy 2013-02-22 22:14:30

相关问题