One feature of Java that I really like is autoboxing, in which the compiler automatically converts between primitives and their wrapper classes.
I'm writing a Core Data application in Objective-C/Cocoa, and I'm finding it frustrating to deal with my integer attributes programmatically. Here's why:
//img is a managed object that I have fetched
NSString* filename = [NSString stringWithFormat:@"image%d.png", [[img valueForKey:@"imageID"] intValue]];
If I happen to forget the intValue
message, which I sometimes do, then the int that gets passed to stringWithFormat:
is actually the pointer value.
The problem is that this happens totally silently--no compiler error or warning. Sometimes I'll spend way too long debugging when this silly, stupid thing is the problem.
Is there a way to change my programming style or my compiler settings to prevent me from getting caught in that trap?
Edit: I wasn't clear about the fact that the above example is just one of many places where I run into trouble. Here's another hypothetical example that doesn't have to do with strings:
Entity CollegeClass
has two integer attributes: courseNumber
and enrollmentLimit
. Let's say I want to compare course numbers:
//classFoo is a NSManagedObjects I've fetched
if ([[classFoo valueForKey@"courseNumber"] intValue] < 400) {
NSLog(@"undergraduate class");
}
Or similarly, suppose I want to compute the average enrollment limit for all the classes in the CS department.