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

klaxamazoo

macrumors 6502
Original poster
Sep 8, 2006
438
0
I'm going through Kochan's "Programming in Objective-C 2.0" and I have a question about Category files.

We learn about Categories in chapter 11 by adding Categories for the Fraction class to main program. I prefer to make the categories a separate file to make things a little easier to navigate, but I can't find a way to make just a .h file in XCode 3.2.3.

Here are my questions:
1) Do I make a category file out of class files?
2) If the category file is separate, do I import the category through the main program or can I call it from my "Fraction" class

Thanks
 
Almost always (or probably always), categories are for extending classes you do NOT have the source code for.

When I make category enhancements for Apple's classes I make .h and .m files named ClassName-Category.h and .m.

Example, category addition to NSString to add the method -(int) hexValue; (similar to -(double) doubleValue;)

I have a file named NSString-HexValue.h
Code:
#import <Cocoa/Cocoa.h>

@interface NSString (HexValue) 
-(int) hexValue;
@end

And a file named NSString-HexValue.m
Code:
#import "NSString-HexValue.h"

@implementation NSString (HexValue)
- (int) hexValue {
	int n = 0;
	sscanf([self UTF8String], "%x", &n);
	return n;
}
@end

And anywhere I want to use that category I just include the NSString-HexValue.h (or not, and get a compiler error but it will work at runtime)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.