Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

teek

macrumors member
Original poster
Feb 12, 2008
88
0
Norway
Is it possible to add a single category to multiple objects?

I have a set of classes which I want to add a "toString" method to but they are in no way related so it feels wrong to subclass just to add this one method and there's just too many classes to simply add the method to each and every one of them.

I know I could just create another class which would do this on any object but the method implementation is going to vary a great deal from object to object.
 
I'll put my neck on the line and say that unless all those classes have a common parent then I don't think there's a way to do this. And to be honest, if "the method implementation is going to vary a great deal from object to object" then I'm not 100% certain on what you want to achieve. Is it a common method that others can replace with something more custom?

It's not a good way to design things, but the most obvious solution is:

Code:
@implementation TEWhatever

+ (id)performSpecialTaskOn:(id)object
{
	if([object respondsToSelector:@selector(performSpecialTask)])
		return [object performSpecialTask];

	return <expression that does the generic version of the task>;
}

A messier in some ways, cleaner in others solution would be to add the relevant methods to the relevant classes programmatically at runtime, according to such rules as you care to use. You need to drop down to C stuff, but Theocacao has a decent enough explanation of the basics.

EDIT:
Actually, this might be a good time to deploy the C preprocessor? E.g.
Code:
#define AddCategoryForClass(c)	\
	@implementation c (CategoryName)	\
	[... whatever ...]	\
	@end

AACategoryForClass(class1)
AACategoryForClass(class2)
... etc ...
 
Presumably all your classes of interest derive from NSObject so you could add your category to NSObject.

What does toString do? Is it different from description?
 
Cool :)

I would have never thought of that ! :)

My toString method will generate a JSON formatted representation of the object.

I just figured it would be easier to add this to the classes I need it for by using a Category.

I don't know, maybe it's plain wrong to use a Category like this.
 
If you have the source code for these classes then something like this would usually be done with a protocol, similar to NSCopying, NSCoding etc.

If these are NS or UI classes then a category may be more convenient. You could obviously subclass the relevant classes or write a utility function that takes an object and generates the JSON representation.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.