iphone - 将GLKVector3添加到NSMutableArray

标签 iphone ios objective-c xcode

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

这是代码示例:

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

谢谢

最佳答案

问题是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

这会将someVector的内容复制到NSValue中,然后再次将它们复制到storedVector中。

如果您希望在数组中保留对valueWithPointer:的引用而不是复制内容,则可以使用pointerValuesomeVector,尽管那样您将需要注意手动内存管理,因此更好的解决方案可能是使用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/

相关文章:

ios - 在适当的部分动态添加行而不干扰其排序

ios - iOS 中的 "error in __connection_block_invoke_2: Connection interrupted"是什么?

ios - 设置 UIButton 的 backgroundImage 时不调整大小,但定位

ios - 如何修复 UICollectionViewCell 中的图像高度?

ios - 通过 iOS 应用内购买定位特定应用

iphone - 如何使用SFHFKeyChainUtils?

ios - 通过索引获取 NSDictionary 键?

iPhone - 用另一个模态视图覆盖一个模态视图

iphone - 为什么我会在生产应用程序中看到 iAd 的广告,就像我在开发时看到的那样?

iphone - Objective-C 和 ASIHTTPRequest - 响应字符串问题