2009-08-27 8 views
14

Uso una raccolta di metodi di categoria per le classi incorporate di Cocoa per semplificarmi la vita. Pubblicherò alcuni esempi, ma voglio davvero vedere che cosa hanno escogitato altri codificatori. Che tipo di pratici metodi di categoria sono ?Che tipo di metodi di categoria utilizzate per rendere più facile la programmazione Cocoa?

Esempio # 1:

@implementation NSColor (MyCategories) 
+ (NSColor *)colorWithCode:(long)code 
{ 
    return [NSColor colorWithCalibratedRed:((code & 0xFF000000) >> 24)/255.0 
            green:((code & 0x00FF0000) >> 16)/255.0 
             blue:((code & 0x0000FF00) >> 8)/255.0 
            alpha:((code & 0x000000FF)  )/255.0]; 
} 
@end 

// usage: 
NSColor * someColor = [NSColor colorWithCode:0xABCDEFFF]; 

Esempio # 2:

@implementation NSView (MyCategories) 
- (id)addNewSubViewOfType:(Class)viewType inFrame:(NSRect)frame 
{ 
    id newView = [[viewType alloc] initWithFrame:frame]; 
    [self addSubview:newView]; 
    return [newView autorelease]; 
} 
@end 

// usage: 
NSButton * myButton = [someView addNewSubviewOfType:[NSButton class] 
              inFrame:someRect]; 
+0

Dovrebbe essere wiki della comunità, penso. – jbrennan

risposta

1

Ho alcuni metodi nifty su NSDate. Questo si spiega da sé:

-(BOOL)isOnTheSameDayAsDate:(NSDate *)date { 

    NSCalendar *cal = [NSCalendar currentCalendar]; 
    NSDateComponents *selfComponents = [cal components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit 
              fromDate:self]; 

    NSDateComponents *dateComponents = [cal components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit 
               fromDate:date]; 

    return (([selfComponents day] == [dateComponents day]) && 
      ([selfComponents month] == [dateComponents month]) && 
      ([selfComponents year] == [dateComponents year])); 

} 

Usage:

if ([aDate isOnTheSameDayAsDate:anotherDate]) { ... } 

Questo fornisce un metodo per ottenere facilmente le date come "09:00 del giorno prima":

-(NSDate *)dateWithDayDelta:(NSInteger)daysBeforeOrAfter atHour:(NSUInteger)hour minute:(NSUInteger)minute second:(NSUInteger)second { 

    NSDate *date = [self addTimeInterval:(24 * 60 * 60) * daysBeforeOrAfter]; 
    NSCalendar *calendar = [NSCalendar currentCalendar]; 

    NSDateComponents *comps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit |   
                NSMinuteCalendarUnit | NSSecondCalendarUnit 
             fromDate:date]; 

    [comps setHour:hour]; 
    [comps setMinute:minute]; 
    [comps setSecond:second]; 

    return [calendar dateFromComponents:comps]; 
} 

Usage:

// We want 9am yesterday 
NSDate *nineAmYesterday = [[NSDate date] dateWithDayDelta:-1 
                atHour:9 
                minute:0 
                second:0]; 
+0

Roba buona. Ho appena iniziato a lavorare con 'NSCalendar' ieri, quindi è perfetto! –

2

Categoria, che aggiunge md5/sha1 hashing su NSString. NSData è simile.

#define COMMON_DIGEST_FOR_OPENSSL 
#import <CommonCrypto/CommonDigest.h> 


@implementation NSString(GNExtensions) 

    - (NSString*) 
    hashMD5 
    { 
     NSData* data = [self dataUsingEncoding: NSUTF8StringEncoding allowLossyConversion: NO]; 

     unsigned char hashingBuffer[16]; 
     char outputBuffer[32]; 

     CC_MD5([data bytes], [data length], hashingBuffer); 

     for(int index = 0; index < 16; index++) 
     { 
      sprintf(&outputBuffer[2 * index], "%02x", hashingBuffer[index]); 
     } 

     return([NSString stringWithCString: outputBuffer length: 32]); 
    } 


    - (NSString*) 
    hashSHA1 
    { 
     NSData* data = [self dataUsingEncoding: NSUTF8StringEncoding allowLossyConversion: NO]; 

     unsigned char hashingBuffer[20]; 
     char outputBuffer[40]; 

     CC_SHA1([data bytes], [data length], hashingBuffer); 

     for(int index = 0; index < 20; index++) 
     { 
      sprintf(&outputBuffer[2 * index], "%02x", hashingBuffer[index]); 
     } 

     return([NSString stringWithCString: outputBuffer length: 40]); 
    } 


@end 
5

ho davvero stato amorevole categoria "KVO+Blocks" di Andy Matuschak su NSObject. (Sì, aggiunge alcune nuove classi internamente come dettagli di implementazione, ma il risultato finale è solo una categoria su NSObject). Permette di fornire un blocco da eseguire quando un valore conforme a KVO cambia piuttosto che dover gestire ogni osservazione KVO nel metodo observeValueForKeyPath:ofObject:change:context:.

+0

+1 è fantastico! –

Problemi correlati