Search code examples
ioscocoa-touchcgpath

How to create a category to extend CGPaths?


I would like to create a category to "extend" the "class" of CGPath and add more functionality. Because CGPath is not a regular object of ObjectiveC how do I do that?

Excuse my lack of knowledge about c/c++


Solution

  • Simple, you just write C functions. You should be careful about name-collisions though, so add a prefix to the names of the function. If you need a function that creates a CGPath from NSData* or sth. like that, you would just declare and implement a C function named RDCGPathCreateWithData(NSData *data) (using RD-prefix for RubberDuck ;D).

    In your header files, just declare the function, and implement them in the implementation files. For my example this would look something like this:

    RDCGPath.h

    #ifndef RDCGPATH_H
    #define RDCGPATH_H
    
    CGPathRef RDCGPathCreateWithData(NSData *data);
    // any other function declarations
    
    #endif
    

    RDCGPath.m

    #include "RDCGPath.h"
    
    CGPathRef RDCGPathCreateWithData(NSData *data) {
        //...
    }
    
    // imlementation of other functions
    

    The preprocessor directives in the .h file are called include guards. They protect you from errors due to having the same declaration multiple times.