我为Cocoa的内置类使用了一组类别方法,使我的生活更轻松.我将发布一些例子,但我真的想看看其他编码员提出了什么.你使用什么样的方便类别方法?
示例#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];
Run Code Online (Sandbox Code Playgroud)
示例#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];
Run Code Online (Sandbox Code Playgroud)
我真的很喜欢Andy Matuschak的" KVO + Blocks "类别NSObject.(是的,它在内部添加了一些新类作为实现细节,但最终结果只是一个类别NSObject).它允许您提供在符合KVO的值更改时执行的块,而不是必须处理方法中的每个 KVO观察observeValueForKeyPath:ofObject:change:context:.
我在 NSDate 上有一些漂亮的方法。这是不言自明的:
-(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]));
}
Run Code Online (Sandbox Code Playgroud)
用法:
if ([aDate isOnTheSameDayAsDate:anotherDate]) { ... }
Run Code Online (Sandbox Code Playgroud)
这提供了一种轻松获取日期(例如“前一天上午 9 点”)的方法:
-(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];
}
Run Code Online (Sandbox Code Playgroud)
用法:
// We want 9am yesterday
NSDate *nineAmYesterday = [[NSDate date] dateWithDayDelta:-1
atHour:9
minute:0
second:0];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
556 次 |
| 最近记录: |