Kevin Vance - So in most sane programming languages, it's pretty easy to manipulate…

Entries | Archive | Friends | Friends' Friends | User Info

08:37 pm

Thursday, April 9th, 2009
Previous Entry Share Next Entry
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[2] += 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:
                      [NSNumber numberWithInt:1],
                      [NSNumber numberWithInt:2],
                      [NSNumber numberWithInt:3],
                      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?!

Link )Reply )

Comments
[User Picture]From: ramoth4
2009-04-10 03:29 am (UTC)
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/
(Reply) (Thread)
[User Picture]From: kvance
2009-04-10 03:54 am (UTC)
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.
(Reply) (Parent) (Thread)
[User Picture]From: ramoth4
2009-04-10 04:59 am (UTC)
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.
(Reply) (Parent) (Thread)
[User Picture]From: kvance
2009-04-10 05:33 am (UTC)
Yes, I thought it seemed very C-like.

Thanks for the suggestion; that looks nice and clear.
(Reply) (Parent) (Thread)
[User Picture]From: ramoth4
2009-04-10 06:05 am (UTC)
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.
(Reply) (Parent) (Thread)