Defining categories for protocols in Objective-C?

Short answer: No.

Long answer: how would this work? Imagine you could add methods to existing protocols? How would this work? Imagine we wanted to add another method to NSCoding, say -(NSArray *) codingKeys; This method is a required method that returns an array of the keys used to encoding the object.

The problem is that there are existing classes (like, say NSString) that already implement NSCoding, but don’t implement our codingKeys method. What should happen? How would the pre-compiled framework know what to do when this required message gets sent to a class that does not implement it?

You could say “we can add the definition of this method via a category” or “we could say that any methods added via these protocol categories are explicitly optional”. Yes, you could do this and theoretically get around the problem I’ve described above. But if you’re going to do that, you might as well just make it a category in the first place, and then check to make sure the class respondsToSelector: before invoking the method.

Leave a Comment