Personal Project

Sunday, October 13, 2013

How do CATEGORIES EXTEND CLASSES ?



Categories are an elegant way to extend any Objective C class without changing original codes. Take a peek at StoreKit framework for example, you can extend SKProduct.h in StoreKit framework as shown below.


SKProduct+ priceWithString.h

#import <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>

@interface SKProduct (priceWithString)                                  // priceAsString : category name
@property (nonatomic, readonly) NSString *priceAsString;      // Extended property    
-(void) printPrice;                                                                         // Extended function


@end


SKProduct+ priceWithString.m

#import "SKProduct+priceAsString.h"

@implementation SKProduct (priceAsString)

- (NSString *) priceAsString
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

    [formatter setLocale:[self priceLocale]];
    
    NSString *str = [formatter stringFromNumber:[self price]];
    [formatter release];
    return str;
}

-(void) printPrice  {    // Extended function

}

@end

No comments:

Post a Comment