你使用什么类型的方法来使Cocoa编程更容易? [英] What kind of category methods do you use to make Cocoa programming easier?
问题描述
我使用Cocoa类的类别方法集合来使我的生活更轻松。我会发布一些例子,但我真的想看看其他编程人员提出了什么。
I use a collection of category methods for Cocoa's built in classes to make my life easier. I'll post some examples, but I really want to see what other coders have come up with. What kind of handy category methods are you using?
示例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];
示例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];
推荐答案
我真的很喜欢Andy Matuschak的 KVO + Blocks 类别 NSObject
。 (是的,它在内部添加一些新的类作为实现细节,但最终结果只是一个类别 NSObject
)。当你在 observeValueForKeyPath:ofObject:change:context:$>中观察KVO时,你可以提供一个块来执行一个符合KVO的值,而不必处理 c $ c>方法。
I've really been loving Andy Matuschak's "KVO+Blocks" category on NSObject
. (Yes, it adds some new classes internally as implementation details, but the end result is just a category on NSObject
). It lets you provide a block to be executed when a KVO-conforming value changes rather than having to handle every KVO observation in the observeValueForKeyPath:ofObject:change:context:
method.
这篇关于你使用什么类型的方法来使Cocoa编程更容易?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!