Is it right way to use Category?

Discussion in 'iOS Programming' started by mikezang, Nov 29, 2010.

  1. mikezang macrumors 6502a

    Joined:
    May 22, 2010
    Location:
    Tokyo, Japan
    #1
    I am not sure if I can post this question here because it is about Objective-C.

    I start to use Category for my special purpose, but I found many time I used '+' class, for example, I want to parse specific Table from HTML, I made a Category for that as below.
    Code:
    #import "Element.h"
    
    @interface Element (ParseTables) 
    + (NSArray *)parseHtml:(NSString *)html forTable:(int)table;
    @end
    
    In fact, it doesn't return a Element or array of Element, it returns of array of NSString, I want to know if this is a right way to use Category, or it is better to let it as a standalone function?:
    Code:
    NSArray *parseHtml(NSString *html, int table);
    
     
  2. Comrade Yeti, Nov 30, 2010
    Last edited: Nov 30, 2010

    Comrade Yeti macrumors newbie

    Joined:
    Nov 3, 2010
    #2
    My personal opinion and style is that if the function has nothing to do with the class, it should not be in the class. It increases the likelyhood that when I look at it months later, I'll understand what it was doing.

    I would make it a plain C function.

    If you insist/want to use categories, I would make it a category of NSArray with a helper name like

    Code:
    +(NSArray*)arrayFromHTML:(NSString*)html andTable:(int)table
    
     
  3. mikezang thread starter macrumors 6502a

    Joined:
    May 22, 2010
    Location:
    Tokyo, Japan
    #3
    I am still not sure which case I should use Category or not, do you have any samples for easy to understand?
     
  4. Comrade Yeti macrumors newbie

    Joined:
    Nov 3, 2010
    #4
    Use categories when you want to add functionality to existing classes. Its normally used to add functionality to the existing Cocoa classes, as sub-classing them can be a lot of work.
     

Share This Page