views:

71

answers:

3

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?

A: 

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.

Jim Buck
+1  A: 

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

blu
Or any Cocoa collection object
JeremyP
indeed, good call
blu
+3  A: 

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.

progrmr
Why do I care that I cannot pass them as objects? Sorry if that's a dumb question coming from an autoboxing universe.
Yar
If you want to call an API that takes an NSNumber object as a parameter or store them in an NSArray or NSDictionary then it has to be an object.
progrmr
I would say basic *scalar* types are preferred. It takes pretty special circumstances for a C array or C string to be preferable over an NSArray or NSString.
Chuck
Thanks @Chuck, @progrmr... that definitely helps give some perspective on the thing. So the last part of my question, whether you need to call `release`?
Yar
No. retain, release, autorelease are only for reference counted objects, never on primitive types.
progrmr