adding category files

Discussion in 'Mac Programming' started by klaxamazoo, Aug 25, 2010.

  1. klaxamazoo macrumors 6502

    Joined:
    Sep 8, 2006
    #1
    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
     
  2. jared_kipe macrumors 68030

    jared_kipe

    Joined:
    Dec 8, 2003
    Location:
    Seattle
    #2
    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)
     
  3. klaxamazoo thread starter macrumors 6502

    Joined:
    Sep 8, 2006

Share This Page