||Thursday, April 9th, 2009
So in most sane programming languages, it's pretty easy to manipulate a list of integers. In python, for example:
a = [1, 2, 3]
a += 1 # Now a == [1, 2, 4]
But I've been using Objective C and Cocoa this week, and... and... well, I must have this wrong:
NSMutableArray *a = [[NSMutableArray arrayWithObjects:
nil] retain]; // a == [1, 2, 3]
[a replaceObjectAtIndex:2 withObject:[NSNumber numberWithInt:[[a objectAtIndex:2] intValue] + 1]]; // Now a == [1, 2, 4]
I have this totally wrong... right?!
That's about the size of it. Objective-C's handling of primitive types does suck, due to the lack of autoboxing.
Suppose there was a better number object that was actually mutable. It's not as bad to do something like:
[[a objectAtIndex:2] add:1];
As far as array creation blowing, I've written some macros to help with that. http://iamthewalr.us/projects/cbobjectcreationmacros/
Those macros look great. Yeah, the nil termination seemed out-of-place to me. It's a language with properties and garbage collection, but don't forget about NULL termination!
In real life, I had an NSDictionary mapping strings to integers, and I couldn't believe the code I ended up with to increment/decrement them.
The nil termination is, as you likely know, due to the braindead nature of C's va_arg nonsense.
Typically, with a dict, I think it'd be more readable to do:
int x = [[dict objectForKey:key] intValue];
x++; // or whatever
[dict setObject:[NSNumber numberWithInt:x] forKey:key];
It's easier that way to just let your eyes glaze over the BS you have to do to get/set and you can just focus on x++; or whatever you end up doing to it.
Yes, I thought it seemed very C-like.
Thanks for the suggestion; that looks nice and clear.
One of the best and worst things about Objective-C is that it's a direct superset of C. "Objects" are just structs with a particular layout; "Methods" are just functions that take two hidden arguments; etc.