Solving the NSInteger <-> NSNumber problem - iphone

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.

Related

Objective-C Data Structures (Building my own DAWG)

After not programming for a long, long time (20+ years) I'm trying to get back into it. My first real attempt is a Scrabble/Words With Friends solver/cheater (pick your definition). I've built a pretty good engine, but it's solves the problems through brute force instead of efficiency or elegance. After much research, it's pretty clear that the best answer to this problem is a DAWG or CDWAG. I've found a few C implementations our there and have been able to leverage them (search times have gone from 1.5s to .005s for the same data sets).
However, I'm trying to figure out how to do this in pure Objective-C. At that, I'm also trying to make it ARC compliant. And efficient enough for an iPhone. I've looked quite a bit and found several data structure libraries (i.e. CHDataStructures ) out there, but they are mostly C/Objective-C hybrids or they are not ARC compliant. They rely very heavily on structs and embed objects inside of the structs. ARC doesn't really care for that.
So - my question is (sorry and I understand if this was tl;dr and if it seems totally a newb question - just can't get my head around this object stuff yet) how do you program classical data structures (trees, etc) from scratch in Objective-C? I don't want to rely on a NS[Mutable]{Array,Set,etc}. Does anyone have a simple/basic implementation of a tree or anything like that that I can crib from while I go create my DAWG?
Why shoot yourself in the foot before you even started walking?
You say you're
trying to figure out how do this in pure Objective-C
yet you
don't want to rely on a NS[Mutable]{Array,Set,etc}
Also, do you want to use ARC, or do you not want to use ARC? If you stick with Objective-C then go with ARC, if you don't want to use the Foundation collections, then you're probably better off without ARC.
My suggestion: do use NS[Mutable]{Array,Set,etc} and get your basic algorithm working with ARC. That should be your first and only goal, everything else is premature optimization. Especially if your goal is to "get back into programming" rather than writing the fastest possible Scrabble analyzer & solver. If you later find out you need to optimize, you have some working code that you can analyze for bottlenecks, and if need be, you can then still replace the Foundation collections.
As for the other libraries not being ARC compatible: you can pretty easily make them compatible if you follow some rules set by ARC. Whether that's worthwhile depends a lot on the size of the 3rd party codebase.
In particular, casting from void* to id and vice versa requires a bridged cast, so you would write:
void* pointer = (__bridge void*)myObjCObject;
Similarly, if you flag all pointers in C structs as __unsafe_unretained you should be able to use the C code as is. Even better yet: if the C code can be built as a static library, you can build it with ARC turned off and only need to fix some header files.

Core Data primitive accessor methods valid for iPhone?

I'm getting mixed signals as to whether primitive accessor methods (of the form setPrimitive*YourAttribute* vs setPrimitiveValue:*value* forKey:#"*YourAttribute*" in Core Data objects are meant for use with iPhone code or just Mac. On the one hand, the Apple documentation doesn't seem to mention them as available for iOS, just Mac OS X v10.5. On the other hand, they work with my iPhone app's code, albeit with compiler warnings, e.g. "Method xxxx not found (return type defaults to 'id')".
Can someone confirm one way or another?
In the Overview of the Managed Object Accessor Methods section of Core Data Programming Guide it states that primitive accessors are automatically generated for you, but you will need to declare the properties to suppress compiler warnings. You say using primitive accessors works in your code (even with the warnings) so it seems like it's supported in iOS.
It appears that Apple's documentation pages aren't always rigorous in mentioning a given feature's availability in the various OSes.
You could use NSNumber instead. For bools you would have and [NSNumber numberWithInt:0] for NO and [NSNumber numberWithInt:1] for YES for example. Same logic with integers, doubles, float. It's much easier this way. Your property would be like: NSNumber *myInteger , you would only have to box and unbox it when you retrieve or store it. That's how I would do it.

Bit fields in Scala

How to simulate bit fields in Scala? The bit fields are used to access some bits of one type (like this in C link). I know it's possible to write with bit operators, but I think there a better way if not consider the performance.
Thanks for every hint that might give.
If you just want single bits, then collection.BitSet will work for you.
If you want a proper bit field class, then you're out of luck for two reasons. First, because Scala doesn't have one. Second, because even if it did, the space savings would probably not be very impressive since the overhead of the enclosing object would probably be large compared to your bits.
There are a couple of ways out of this with some work: a custom-defined class that wraps an integer and lets you operate on parts of it as bit fields; when you go to store the integer, though, you just have it saved as a primtive int. Or you could create an array of bit field structs (of arbitrary length) that are implemented as an array of integers. But there's nothing like that built in; you'll have to roll your own.
Sadly not... The shift operators and bitwise boolean operators are pretty much all you've got.
There's also this repo,
word-aligned compressed variant of the Java bitset class. It uses a 64-bit run-length encoding (RLE) compression scheme.
http://code.google.com/p/javaewah/

Using Structs in Objective-C (for iOS): Premature Optimization?

I realize that what counts as premature optimization has a subjective component, but this is an empirical or best-practices question.
When programming for iOS, should I prefer using struct and typedefs where the object has no "behavior" (methods, basically)? My feeling is that the struct syntax is a bit strange for a non-C person, but that it should be WAY lower profile. Then again, testing some cases with 50K NSObject instances, it doesn't seem bad (relative, I know). Should I "get used to it" (use structs where possible) or are NSObject instances okay, unless I have performance problems?
The typical case would be a class with two int member variables. I've read that using a struct to hold two NSString instances (or any NSObject subclass) is a bad idea.
Structs with NSObject instances in them are definitely a bad idea. You need -init and -dealloc to handle the retain count correctly. Writing retain and releases from the caller side is just insane. It will never pay off.
Structs with two int or four doubles are borderline cases. The Cocoa framework itself implements NSRect, NSPoint etc. as a struct. But that fact has confused lots and lots of newcomers. Honestly, even the distinction between primitive types and object types confused them. It becomes even confusing to me when you have structs as properties of an object: you can't do
object.frame.origin.x=10;
If you start making your own structs, you need to remember which is which. That's again a hassle. I think the reason why they (NSRect etc.) are structs are basically historical.
I would prefer to make everything objects. And use garbage collection if available.
And, don't ask people if something is worth optimizing or not. Measure it yourself by Instruments or whatever. Depending on the environment (ppc vs intel, OS X vs iOS, iPad vs iPhone) one way which was faster in a previous system might be slower in a new system.
An Objective C object has almost the same storage as a struct, except it is 4 bytes (8 bytes on 64 bit) bigger. That's it - just one pointer into a place where the runtime holds all the class information.
If you are that tight on memory, then lose the 4 bytes, but usually that's only for large numbers of objects: 50,000 Nsobjects vs structs is only 200k - you get a lot of stuff for that 200k. For a million objects, the cost will add up on an iPhone.
If you want to say transfer the items to openGL or need a c array for other purposes, then another option is to make ONE NSObject that has a malloc'ed pointer to all 50,000 integers. Then the objective c memory overhead is ~0, and you can encapsulate all the nasty malloc and free() stuff into the innards of one .m file.
Go with regular objects until you hit a measurable performance bottleneck. I’ve used high-level code even in tight game loops without problems – messaging, collection classes, autorelease pools, no problems.
I see no problem at all with using structs to hold small quantities of primitive (i.e. non object) types where there is no behaviour required. There are already several examples of this in the Cocoa frameworks (CGRect, CGSize, CGPoint, NSRange for example).
Do not use structs to hold Objective-C objects. It complicates the memory management in the reference counted environment and may break it altogether in the GC environment.
For me, I would prefer to use regular objects because you can easily do Object job with it like retain, release, autorelease. I only see quite few structs in Cocoa Framework like CGSize, CGRect and CGPoint. I think the reason is that they are being used a lot
I believe is a good idea to use structs specially if you are dealing with C-based frameworks , lets says OpenGL, CoreGraphics, CoreText specially stuff that will require a couple/triple of ints, doubles, chars, etc. (If they are already not implemented in some of Apple Frameworks: CGRect, CGPoint, CTRect, NSRange, etc...) C stuff plays and looks better with other C stuff.
I don't think I would write a subclass of NSObject containing a couple of ints. It's almost ridiculous. lol.

iPhone: Data structure choice

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.