Friday, December 04, 2009

A What?!

Objective-C has a concept called "Categories" - I just learned about these things a couple of days ago listening to a podcast and wasn't quite sure when or where it would be appropriate to use something like this.

At a high level a "Category" is a way to change (add or modify) the behavior of an existing object. For example - if you needed to print a string backwards in your application; one option would be to subclass the string object. Another option would be to create a category to add a method to perform this operation.

The benefit of a category is that the new method is available to all of the Objects of that type. Another cool benefit is that you don't have to change any code at all to take advantage of the behavior change. All types of the categorized object get the new behavior.

The downside to this? I'm not sure it seems pretty powerful but as they say "with great power comes a great responsibility"

Here is the problem and the solution I solved by using categories:

(IMHO) The Apple API has a bug in the MapKit. If you add a MKPinAnnotationView the CallOut has a (seemingly) random z-index defined which causes the following to happen:

You can see the red pins are on top of the call out window. Very irritating - I was about to give up when I googled one last time and found this posting. Here is how I fixed it by using a category:

Here is the header:

#import <MapKit/MapKit.h>


@interface MKPinAnnotationView (ZIndexFix)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
@end

and here is the Implementation:

#import "AEBMapViewCategory.h"


@implementation MKPinAnnotationView (ZIndexFix)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.superview bringSubviewToFront:self];
[super touchesBegan:touches withEvent:event];
}
@end

So basically I overrode the default behavior of the [touchesBegan: withEvent:] method.

That is all the code I changed to make the picture above look like this:

Pretty sweet huh?

If anyone else solved this problem differently I'd love to hear about it.

-Aaron


No comments: