几周前我回答了一个非常相似的问题。为这个问题编辑了下面的答案。
一般来说,我会避免 NSInvocation 进行此类工作。这往往是一个令人头疼的维护问题,尤其是在未来的重构中造成困难。
首先,给定这个方法:
-(void)plotPoly:(Polygon *)poly WithColor:(UIColor *)color AndFill:(BOOL)filled;
一般会这样声明:
-(void)plotPoly:(Polygon *)aPoly color:(UIColor *)aColor filled:(BOOL)filledFlag;
这更符合命名约定。
现在,我要做的实际上是将参数捕获到一个提供-invoke 方法的简单类中。
类似这样的界面的东西:
PolyPlotter.h:
@interface PolyPlotter : NSObject
{
Polygon *poly;
UIColor *color;
BOOL filled;
}
+ plotterWithPoly: (Polygon *) aPoly color: (UIColor *) aColor filled: (BOOL) filledFlag;
- (void) plot;
@end
PolyPlotter.m:
@interface PolyPlotter()
@property Polygon *poly;
@property UIColor *color;
@property BOOL filled;
@end
@implementation PolyPlotter
@synthesize poly, color, filled;
+ plotterWithPoly: (Polygon *) aPoly color: (UIColor *) aColor filled: (BOOL) filledFlag;
{
PolyPlotter *polygonPlotter = [PolyPlotter new];
polygonPlotter.poly = aPoly;
polygonPlotter.color = aColor;
polygonPlotter.filled = filledFlag;
return [polygonPlotter autorelease];
}
- (void) plot;
{
// ... do your plotting here ...
}
@end
使用很简单。只需创建一个 PolygonPlotter 实例并告诉它在延迟后或在主线程或其他任何地方执行选择器plot。
鉴于这个问题,我怀疑您在绘图时可能需要更多背景信息?如果是这样,您可以将该信息作为参数传递给-plot,例如将方法声明为:
- (void) plot: (UIView *) aViewToPlotIn;
或者类似的东西。
就像我说的,代码稍微多一些,但比 NSInvocation 模式更加灵活和可重构。例如,您可以很容易地将 PolygonPlotter 制作成可以存档的东西。