Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

Should NSArray and NSMutableArray be always used instead of normal C arrays?

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

Answers (2)

CRD
CRD

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 doubles in Obj-C.

C# arrays of unboxed doubles (same hold for other primitive types and structures) are someway between Obj-C double[] and an NSArray of NSNumbers - 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 NSArrays of NSObjects.

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 NSArrays.

  • 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 NSNumbers have a high overhead compared to the same number of doubles) 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 NSArrays.

Upvotes: 2

ikuramedia
ikuramedia

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

Related Questions