Dan Rosenstark
Dan Rosenstark

Reputation: 69777

When to use primitives in Objective-C?

When should I use primitives in Objective-C instead of NSValue subclasses? This code is certainly cleaner (I think) than using NSNumber:

    float width = sliderOne.frame.size.width;
    float totalWidth = width * 2 + 10;

but are there any drawbacks? Also, is it correct that I don't need to call release or anything with primitives? Does the memory get freed when they go out of scope, then?

Upvotes: 5

Views: 1287

Answers (3)

progrmr
progrmr

Reputation: 77251

The basic types are preferred. Only use the NSNumber and NSValue objects when you have to pass them as an object.

The only drawback to the primitive types are that you can't pass them as an object.

Primitive types can be allocated on the stack (local variables) or the heap (w/malloc). Objects can only be allocated on the heap, which is more expensive that stack allocation.

Upvotes: 4

blu
blu

Reputation: 13175

A main drawback of using primitive types is that you can't store them in an NSArray.

Upvotes: 2

Jim Buck
Jim Buck

Reputation: 20724

Whatever is more convenient for you to use in your own code, but typically you would use NSwhatever when it needs to be passed to some API.

Upvotes: 0

Related Questions