Reputation: 12184
I have a piece of code in C# and I am rewriting it in Objective C. The code uses arrays a lot like double[]and also array of Point structure. so shall i simply used C style array to store Objective C double and CGPoint for my task OR is it a good practice to use NSArrays or NSMutableArrays every time along with NSValue or NSNumber to store non-objects in them.
I could well use a plain array, but again this array is generated at runtime depending upon the size, so shall I use malloc and free to accomplish the same ?
NOTE: http://www.codeproject.com/KB/graphics/BezierSpline.aspx
This the C# code, I am trying to implement in Objective C, if anyone has a converted code, please help me out. I tried but, doesn't seem to work for me.
Upvotes: 2
Views: 444
Reputation: 53000
You are converting from C#, in that language you can have both arrays of unboxed primitive types and structures, e.g. double
, and arrays of boxed types, e.g. equivalent to NSNumber
objects containing double
s in Obj-C.
C# arrays of unboxed double
s (same hold for other primitive types and structures) are someway between Obj-C double[]
and an NSArray
of NSNumber
s - in C# elements are unboxed (as in double[]
) while the array itself is a managed object (as in NSArray
).
C# boxed arrays are equivalent to NSArray
s of NSObject
s.
How do you choose?
If the C# code has fixed-sized arrays of unboxed types use (Obj-)C arrays.
If the C# code as varying-size arrays of boxed types use Obj-C NSArray
s.
If you are happy with C++ for variable-sized arrays of unboxed types consider vector
.
And for everything else balance the cost of boxing each element (10,000 NSNumber
s have a high overhead compared to the same number of double
s) vs. managing the memory for the array (malloc
/free
vs. alloc
/release
vs. ARC/GC). In general, but not as an absolute rule, arrays of unboxed types are best as C arrays while arrays of boxed types are best as NSArray
s.
Upvotes: 2
Reputation: 6058
While its usually better to use NS objects, when you have collections of 'non-objects' it's a trade-off between managing the memory yourself using malloc/free, or coercing non-object data into a storable object. Remember NSArray and so forth will only store NSObjects. For double you can use NSNumber as a container. For CGPoint and other structs, you can either create a new object type or coerce into an NSData object somehow.
Upvotes: 1