In my iPhone app I employ NSDecimalNumber to store some some currency rate values.
I pull the data from the web the first time the app is launched and then again when they become obsolete, and I store them in a NSDictionary; then I use writeToFile:atomically:.
When the app is launched for the first time, my rate conversion method works allright. Yet, when I launch the app a second time, and the rates get loaded with -(NSDictionary*) initWithContentsOfFile: the conversion methos stops working, and I get weird results.
I did some debug with breakpoints in the incriminated method, and I found out that the rates data are seen as NSCFNumber, rather than as NSDecimalNumber. So it appears that initWithContentsOfFile doesn't assign the right class to my objects. For the record, the actual value of these objects, as shown in the description method, corresponds to the expected rate value.
I also checked the plist file generated by writeToFile:atomically:, and saw that the rates are stored as real; I wonder whether this is the right type.
Any idea of whats going on?
Thanks in advance,
Davide
Property lists don't distinguish between decimal numbers and floating-point numbers. The real element holds a floating-point number. (Indeed, the serialization itself may simply be NSNumber sending floatValue to itself, unaware that the instance is actually of a subclass. That would mean the conversion to floating-point happens when you generate the plist data, not when you read it back in.)
You'll have to store it as a string, I think. Hopefully, that's lossless.
Plists only work with certain data types and NSNumber is one of those. If you want the NSDecimalNumber then you have two ways to go about it. The first is to keep using plists and then convert all the NSNumbers to NSDecimalNumbers after load. The second is to switch to using NSKeyedArchiver for storing data. This requires more code but means that if you save an NSDecimalNumber, you'll get an NSDecimalNumber back.
Related
There is a constant I'm using from the iOS SDK. I printed out the value of the constant (which were int's) and it was 0. Can I assume that constant will always remain zero between iOS builds? The reason I need to use the actual value and not the constant directly is because I want to keep it in a plist that ships in the main bundle. And since a plist doesn't take a constant variable name, I need to place a constant value in the plist.
You shouldn't assume an enum won't change its value, just to be safe, even though it probably won't. (They'll almost certainly keep it constant so old apps run correctly on future OS versions.)
Instead, save a string to your plist (say, "standard" under the key "map type"), and then initialize the actual value at runtime with an if statement. This has the added benefit of actually saying what you mean explicitly, which makes it easier to look at your plist (and your code!) and see what it does.
It's very likely that it will stay the same for at least the life of your application, if not longer.
I've written a large social networking iPhone application, and one of the biggest issues I run into is the fact that NSInteger (and all the other NS-non-object types) are not first class citizens. This problem stems from the fact that, obviously, they have no representation for a nil value.
This creates two main problems:
Tons of overhead and opaqueness to convert to and from NSNumber when storing/retrieving from a collection.
Can't represent nil. Oftentimes, I want to be able to represent an "unset" value.
One way to solve this is to use NSNumber all the time, but that gets extremely confusing. In a User model object, I would have about 20 different NSNumbers, and no easy way to tell if each one is a float, integer, bool, etc.
So here are my thoughts for potential solutions and the pros/cons. I'm not really sold on any of them, so I thought I'd ask for feedback and/or alternative solutions to this problem.
Continue to use NSInteger types, and just use NSIntegerMax to represent nil.
PRO - Less memory overhead
PRO - Clear typing
CON - NSIntegerMax is not really nil. If programmers aren't careful or don't know this convention, invalid values could leak into the display layer.
CON - Can't store them in a collection without conversions in and out
Use NSNumber and designate types using hungarian notation (eg NSNumber fHeight, NSNumber iAge)
PRO - First-class citizens
PRO - Nil problem solved
CON - Increased memory overhead
CON - Lose compiler type checking
CON - Hungarian notation is contentious
Write my own first-class primitive object types (think Java http://developer.android.com/reference/java/lang/Integer.html)
PRO - First-class citizens
PRO - Nil problem solved
PRO - Keeps compiler type checking
PRO - Objects will be simpler than NSNumber. Internal storage will specific to data type.
CON - Increased memory overhead
CON - Sacrifices a bit of code portability and compatibility
Looking for a convincing argument in favor of one of these techniques, or one I haven't thought of if you've got one.
UPDATE
I've gone ahead and started an open source project (Apache 2.0), into which I'll be pulling a number of our internal classes as I have time. It currently includes object wrappers for some of the more common native data types (BOOL, CGFloat, NSInteger, NSUInteger). We chose to do this because it upgrades these data types to first class citizens with strict typing. Maybe you disagree with this approach, but it has worked well for us, so feel free to use it if you want.
I'm adding other classes we've found uses for, including a disk-backed LRU cache, a "Pair" object, a low memory release pool, etc.
Enjoy
github - Zoosk/ZSFoundation
The most common convention for representing the idea of nil as an NSInteger is to use the NSNotFound value. This is, in fact, equal to NSIntegerMax, though it tends to be more obvious to the reader that this is a sentinel value representing the lack of a number. There are many cases where this is used throughout Cocoa. One common case is as the location field of an NSRange as a return value from -rangeOfString: et al.
You could try this?
#define numberWithFloat(float f) \
[NSNumber numberWithFloat:f]
#define floatFromNumber(NSNumber *n) \
[n floatValue]
(see my original answer below)
Here's the other thing with NSNumber, you don't have to retrieve what you set.
For example
NSNumber *myInt = [NSNumber numberWithInteger:100];
float myFloat = [myInt floatValue];
is perfectly valid. NSNumber's strength is that it allows you to "weak-type" your primitives, use compare:, use isEqualTo:, and stringValue for easy display.
[EDIT]
User #Dave DeLong says that sub-classing NSNumber is a Bad Idea without much work. Since it's a class cluster (meaning NSNumber is an abstract superclass of a lot of subclasses) you'll have to declare your own storage if you sub-class it. Not recommended, and thanks to Dave for pointing that out.
As an alternative, there is also the NSDecimal struct for representing numerical types. NSDecimal (and its Objective-C class version NSDecimalNumber) lets you represent true decimals and avoid floating point errors, so it tends to be recommended for dealing with things like currency.
The NSDecimal struct can represent numbers as well as a Not a Number state (a potential nil replacement). You can query whether an NSDecimal is not a number using NSDecimalIsNotANumber(), and generate the Not a Number value with the help of an NSDecimalNumber.
NSDecimals are faster to work with than NSDecimalNumbers, and the structs don't bring the same kind of memory management issues that objects do.
However, there isn't an easy way to get values into NSDecimal form without using a temporary NSDecimalNumber. Also, many of the math functions (like trigonometry operations) that are available for simple floating point numbers aren't yet available for NSDecimal. I'd like to write my own functions that add some of these capabilities, but they would require accessing the internal fields of the struct. Apple labels these as private (with the use of an underscore), but they are present in the headers and I'd guess they're unlikely to change in the future.
Update: Dave DeLong wrote a series of functions for performing NSDecimal trigonometry, roots, and other operations. I've tweaked these to provide up to 34 digits of decimal precision, and the code for these functions can be downloaded here. As a warning, this precision comes at a price in terms of performance, but these functions should be fine for fairly infrequent calculations.
I don't understand why, if you store stuff as an NSNumber, you need to care what type it is. NSNumber will choose an appropriate internal representation and then do any necessary conversion depending on what format you ask for its value in.
If you can't tell what type is appropriate from the name of the variable you need to choose better names. e.g.
numberOfChildren = [NSNumber numberWithFloat: 2.5];
is plainly silly.
And for currency values, I definitely recommend using NSDecimalNumber (which is a subclass of NSNumber) but defines base 10 arithmetic operations so you don't have to worry about float rounding.
Reading the documentation, I would have to do something ugly like this:
NSLocale *usLocale = [[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"] autorelease];
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:#"0.00001" locale:usLocale];
But: Isn't there a nicer way of telling that NSDecimalNumber class to look out for the period (.) instead of anything else? Locales feel so unsafe to me. What if one day a new president thinks to be so cool to change the period symbol from . to ,? Then my app crashes. Sure this won't happen so likely. But there is a little chance it could. Enough to scare me using a locale for this ;-)
Any idea? Or is that my only option? And if it is the only option: Is the above approach correct? Or is there even a better one?
And: If I get that right, the NSDecimalNumber object will read that string, parse it and create the mantissa, exponent and isNegative values out of it for internal use, right?
EDIT: I should have mentioned that I add those values programmatically / manually (in my code), they're not user input.
Specifying the locale is only necessary if you're passing in a string that isn't a valid decimal number in the default locale. If your users are creating the strings, it's highly likely that they'll format them properly for the locale they're using.
Using locales is far safer than not using them. Trying to parse the "." out of "1,50" is not likely to succeed.
And considering that
[NSDecimalNumber decimalNumberWithString:#"0.00001" locale:usLocale]
is described in the docs as
Creates and returns an NSDecimalNumber
object whose value is equivalent to
that in a given numeric string.
I think it's a safe bet that it creates and returns an NSDecimalNumber whose value is equivalent to that of the string.
Locales are a Good Thing; if the president were to change the decimal point from . to ,, the en_US locale would be updated by the next release of the OS -- you don't explicitly mention the locale's decimal point in the above code, so you're OK there. That being said you might want to get the system locale instead of specifying en_US explicitly, which will be wrong anywhere outside the US.
If you're worried about the string, it should be coming from a user in which case they'll use their locale-specific decimal point, which should match up. If you're trying to initialize an NSDecimalNumber this way I suppose you could, but I would imagine there are easier ways to skin that cat.
And yes, if you get it right, the result will be an NSDecimalNumber object whose value is equivalent to the string you passed in.
Locales are a Good Thing. Changeable locales applied to static internal data are a Bad Thing, and you're right (if possibly paranoid :D) to be concerned about applying a locale to data you (rather than the user) provides. Here are some solutions that do not rely on applying locales to your internal data.
number = [NSDecimalNumber decimalNumberWithMantissa:1 exponent:-5 isNegative:NO];
number = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithDouble:0.00001] decimalValue];
The second would be very easy to turn into a NSDecimalNumber category implementing -decimalNumberWithDouble:. Probably quite useful.
I think that sqlite3 is a little overkill in complexity for my purpose. I have a really tiny app that takes very tiny input from the user. Inputs are floating point values, dates and integers. I'd say even a hardcore user will generate not more than 10 kb of data with that app.
The object graph can be described pretty good with an calculator example. Imagine a calculator, that stores all calculations. Nothing cool/special. The object graph is like this: An NSMutableArray which stores instances of MyCalculationData objects. Every MyCalculationData object just stores simplest stuff: The mathematic operation used (identified by an integer that is mapped programmatically to something, i.e. "minus" or "division"), the entered value as CGFloat, a timestamp (just a big double, I think).
At the end, this whole NSMutableArray represents one session with that calculator, and the user can re-open it at any time. It gets stored in another NSMutableArray that holds all these calculation sessions.
In theory that's similar to what my app does.
So what are the options?
sqlite3: Too hard to use efficiently. Really. It's just hard, like trying to eat a 20 weeks old bread.
sqlite3 + FMDB: Sounds actually good. Having an objective-c wrapper class to get rid of all this c >> objective-c >> c conversions and restrictions. But: No documentation found. No examples found. No tutorials. Not much used / not much discussed.
CoreData: Maybe in one year, but not at this time. Don't believe in the statistics. Will not upgrade to 3.0 so fast.
Does anyone have good experience with one of those NSFooBarSerialization things?
Have a look at NSKeyedArchiver/Unarchiver. As long as everything in your array conforms to the NSCoding protocol (NSStrings and NSNumbers already do) you can just save your array to disk like this:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myArray];
[data writeToFile:#"/a/path/to/myFile" atomically:YES];
You can load it back like this:
NSData *data = [NSData dataWithContentsOfFile:#"/a/path/to/myFile"];
NSArray *myArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
This method is simple and easy for simple applications such as yours.
I need to keep track of a bunch of objects that can be identified by two keys (Latitude and longitude actually, but there are some other properties). I need to do things like search for a particular object by those two keys, updating it if it is there and inserting if not. I was thinking. I was looking at NSDictionary and NSSet but thought I would hear what the masses have to say.
I guess the simpler way is to use NSDictionary. You will be able to get your data by just doing [dic objectForKey:key].
Also, a good practice is to create some defines for the keys, so that it's easier to change a key name, and also avoids typo:
#define kObjectLatitude #"Latitude"
#define kObjectLongitude #"Longitude"
[object setObject:lat forKey:kObjectLatitude];
[object setObject:lon forKey:kObjectLongitude];
Don't forget to write the defines in a smart place. If you use it only in one class, just write them at the top of the declaration. If, however, you need them through different part of your code, you might consider moving it to the header file of the main class, or a specific header file for defines :)
NS(Mutable)Set will not be useful for you in this case. NSSets are mathematical sets, and you cannot access a specific data with a specific key (aka, you can't ask a set: "Hey, give me the longitude, where-ever you stored it!")
This is not a direct answer, but a word of warning. Latitude and longitude are CLLocationDegrees, which is a double precision floating point value. Testing for equality on floats is a risky proposition since floating point math is inexact. You can easily have an equality test fail on two floats that should theoretically be equal. I don't know the requirements of your application, but you may want to test for proximity rather than equality.
Use NSDictionary. That's what it meant for.