Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumber vs Int

If integers cannot be written to a dictionary and then to a .plist, but NSNumbers can is it better to use NSNumbers throughout the app, rather than needing to convert every-time saving or loading a dictionary from a .plist?

like image 463
user773578 Avatar asked Jul 12 '11 10:07

user773578


People also ask

What is an NSNumber?

NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char , short int , int , long int , long long int , float , or double or as a BOOL .

What is NS integer?

NSInteger is a simply an integer, NSNumber is an object where as int is a primitive data type. NSInteger is nothing more than a synonym for a long integer. If you need to store a number somewhere, use NSNumber.


1 Answers

As a generalization: Just stick with POD types until you need to use an object based representation, such as NSNumber. The performance is much better with the PODs, but you'll need NSNumber in some cases.

In some cases, it may make sense to use NSNumber instead -- this is typically when you reuse a NSNumber often -- this is to avoid making a ton of duplicate NSNumbers. Such occurrences are practical only rarely beyond serialization and generic objc interfaces (bindings, transformers, dictionaries).


Update/Details: The ObjC runtime will in some cases, on some architectures, and on some OS versions substitute a tagged pointer representing NSNumbers of specific type and domain. Although the internal representation has changed since originally written a few years back, here is a good introduction to the subject: http://objectivistc.tumblr.com/post/7872364181/tagged-pointers-and-fast-pathed-cfnumber-integers-in. Where this can be used, it saves you from slow operations like allocations, locking, and ref count ops. Nevertheless, tagged pointers are incapable of representing every number and it introduces overhead, so you should still favor basic builtins over NSNumber as a default. Tagged pointers are a great optimization where applicable, but are far from competing with the builtins when you just need a number.

like image 60
justin Avatar answered Sep 19 '22 07:09

justin