2013-02-22 114 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

相關問題