Skip to content

Instantly share code, notes, and snippets.

@rudyjahchan
Created January 23, 2012 02:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rudyjahchan/1660134 to your computer and use it in GitHub Desktop.
Save rudyjahchan/1660134 to your computer and use it in GitHub Desktop.
Monkey-Patching iOS with Objective-C Categories Part I: Simple Extensions and Overrides
#import <Foundation/Foundation.h>
@interface AClass (ACategory)
@end
#import "AClass+ACategory.h"
@implementation AClass (ACategory)
@end
#import "NSDate+Formatting.h"
@implementation EntryCell
...
@end
#import "NSDate+Formatting.h"
#import "UIFonts+MyFonts.h"
#import "UIViewController+Tourbot.h"
3 minutes ago
#import <Foundation/Foundation.h>
@interface NSDate (Formatting)
- (NSString*) timeAgoInWords;
@end
#import "NSDate+Formatting.h"
@implementation NSDate (Formatting)
- (NSString *)timeAgoInWords {
double seconds = [self timeIntervalSinceNow];
seconds = seconds * -1;
if(seconds < 1) {
return @"now";
} else if (seconds < 60) {
return @"less than a minute ago";
} else {
NSUInteger difference = 0;
BOOL pluralize = NO;
NSString* unit = @"";
if (seconds < 3600) {
difference = round(seconds / 60);
unit = @"minute";
} else if (seconds < 86400) {
difference = round(seconds / 3600);
unit = @"hour";
} else if (seconds < 604800) {
difference = round(seconds / 86400);
unit = @"day";
} else if (seconds < 2592000) {
difference = round(seconds / 604800);
unit = @"week";
} else if (seconds < 31557600) {
difference = round(seconds / 2592000);
unit = @"month";
} else {
difference = round(seconds / 2592000);
unit = @"year";
}
if (difference > 1) {
pluralize = YES;
}
return [NSString stringWithFormat:@"%d %@%@ ago",
difference,
unit,
(pluralize ? @"s" : @"")];
}
}
@end
- (NSString*) description {
return [self timeAgoInWords];
}
#import <Availability.h>
#ifndef __IPHONE_3_0
#warning "This project uses features only available in iPhone SDK 3.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#import <CoreText/CoreText.h>
#import "Extensions.h"
#endif
NSDate* oldDate = [NSDate dateWithTimeIntervalSinceNow:180];
NSLog(@"Date was %@", oldDate.timeAgoInWords);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment