Archive for June 2009


Fun with KVC

June 30th, 2009 — 10:33am

[Warning: this article is for entertainment purposes only. Any harm you do to your code or any offense you incur on the sensibilities of other programmers is your responsibility.]

Some time ago, Guy English posted a great and twisted article on key value coding (KVC). He comes up with a nice hack to do stuff with KVC that was never intended. Of course, there are some neat ways you can use KVC without indulging in the craziness that Guy English delves into (and I think he’d be the first to admit that it’s not meant for primetime). The main point remains, which is that using KVC with NSArrays is a great way to avoid coding loops over their contents. You have an array of “Person” objects and want an array of their names (accessible via a -name method)? Just do…

newArray = [array valueForKey:@"name"];

Now, the keys do not necessarily have to be properties of the object. There’s nothing stopping you from calling other methods on your objects that return other objects, provided they don’t require any arguments. For instance, if starting out with an array of strings…

newArray = [array valueForKey:@"lowercaseString"]

…will generate a new array of lowercase versions of the original strings. Actually, the methods don’t even have to return objects. Want to convert an array of numbers in string form to numbers? Try the following:


array = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", nil];

newArray = [array valueForKey:@"intValue"];

This gives you an array of NSNumbers. KVC auto-boxes scalar types as needed. It’s a great way to do conversions/transformations of arrays of objects in one fell swoop.

Suppose you want to do a deep(er) copy of an array of objects (not only copy the array, but each of its objects as well):

newArray = [array valueForKey:@"copy"];

There is the issue, though, that the copies in the array now have a retain count of 1 and will be leaked unless extra care is taken. But no need write a loop to autorelease the objects. Instead, we can use keypaths to create chains:

newArray = [array valueForKeyPath:@"copy.autorelease"];

Retain it now and release it later or just let it get autoreleased. Either way, everything cleans up nicely.

And if you have a bunch of NSMutableCopying-conformant, immutable objects and want to convert them to their mutable counterparts:

newArray = [array valueForKeyPath:@"mutableCopy.autorelease"];

That gives us an array of autoreleased mutable copies.

Sure, not super mind-blowing but hopefully something above may save you some keystrokes. If you have your own KVC tricks, post them here in the comments.

[Update 2009-06-30]

This all started out with an conversation I had with Guy about wacky KVC stuff. The original title of this post was “KVC Abuse” but after a few edits, it got lost. I added the warning at the top but I’ll make it clear here: this is an abuse of KVC. This whole post is an indulgence.

I avoided a whole discussion of implementing HOM (Higher Order Messaging) type functionality in Objective-C but here’s a method you can use in an NSArray category:

- (NSArray *)map:(SEL)selector
{
	NSMutableArray		*result;
	
	result = [NSMutableArray arrayWithCapacity:[self count]];
	for (id object in self)
	{
		[result addObject:[object performSelector:selector]];
	}
	return result;
}


You don’t get the auto-boxing or the keypath stuff but the end result is still succinct and convenient for the basic case:


newArray = [array map:@selector(lowercaseString)];

Of course, my own version that I use has a more verbose method name (-transformedObjectsUsingSelector:) but no matter how you slice it, it will generate less bile from other developers.

6 comments » | Cocoa, OS X, Programming

413 days

June 19th, 2009 — 1:42pm

No, not the number of days since I last posted, though yes, it’s been a while. I just happened to be looking at my server stats and noticed that I had an uptime of 413 days. I guess this post would have been more timely and poetic at the 1 year mark but I have to say that I’m pretty impressed with Slicehost (warning: it’s affiliate link so if you sign up using that link, I get some credit). The reboot of my slice way back when was when I upgraded to a bigger slice.

I’m sure other people on other providers can post similar numbers but seeing as I had come from DreamHost, I find it pretty amazing. And yes, that is an affiliate link as well as I still use them for other things – I can be a whore at times, too.

Looking back over the past 413 days, I only recall contacting Slicehost support once, and that was for an administrative issue. I do remember some network problems once but those were resolved within minutes. By the time I asked around in the IRC channel about it, it was fixed. For the most part, I almost never think of Slicehost. The fact that I can take them for granted says something about their reliability.

How have the other services and tools I’ve been using on my site fared during this time?

PotionStore has been great. And now that it has an in-app Cocoa store component, it’s even better. I’ve currently integrated it into the latest Hazel beta (forum account required) if you want to see it in action. Just keep in mind that while the app is beta, it is connected to the live store so all sales are real.

Between the two main transaction processors I use, PayPal has been far better than Google Checkout. Very few issues with the former (knock on wood). Unfortunately, when there has been an issue with Google Checkout, I’ve had to hunt to find a way to even contact them and then the email support has been pretty crummy. On the flip side, I can find PayPal’s phone number quickly and their support people seem very knowledgeable and when the call is over, the issue is resolved. Fortunately, Google Checkout accounts for a small number of sales.

For server monitoring, I have been using Montastic. At least, I thought I was. Recently I checked my account only to notice that it wasn’t really monitoring. After unwedging it, it seemed to not like my store certificate, bugging me with alerts regularly. It also seemed to be sending MIME mail of some sort which end up as MMS on my phone. They’ve got pics of my server on fire or something? Annoying and potentially expensive. I’ve disabled it so suggestions for an alternate server monitoring service are welcome.

I could end this post with “Here’s to another 413 days” but I know I have to do a server upgrade at some point which will break my streak. Nonetheless, it’s good to know that downtime occurs on my terms and not my provider’s.

4 comments » | System Administration

Back to top