views:

56

answers:

1

I have stack category for NSMutableArray that I use in Class A

@implementation NSMutableArray (StackUtil)

- (void)push:(id)stackObject {

 [self addObject:stackObject];
}
- (id)pop {

 id retVal = [[self lastObject]retain];
 [self removeLastObject];
 return [retVal autorelease];
}

@end

How do I properly include this category for for Class B which is unrelated to Class A? Also I noticed that when I #import Class A into the header for Class C the category methods work, but I get the " object may not respond to push message" warning. Could someone clear up how categories are "reused" and why they have names (StackUtil in this case), and how they are used.

+5  A: 

You should have a corresponding @interface NSMutableArray (StackUtil) in a header file that declares the category. Importing that header should be enough to confer use of your new methods onto any NSMutableArray in the scope of the import.

@interface NSMutableArray (StackUtil)
- (void) push:(id)stackObject;
- (id) pop;
@end

Certainly the @interface, and usually the @implementation, should be in files of their own, independent of your classes A, B and C, since they are general purpose additions, not something belonging to one of those client classes.

walkytalky
Yes! Defining the category in the interface is what I missed. It seems really basic now that I think about it. Hopefully this post will help others new to categories.
ghostsource