Sag*_*ari 2 iphone objective-c nstimer
-(void)setX:(int)x andY:(int)y andObject:(Sprite*)obj
{
[obj setPosition:CGPointMake(x,y)];
}
Run Code Online (Sandbox Code Playgroud)
现在,我想使用以下计时器调用上面的方法.
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector() userInfo:nil repeats:NO];
Run Code Online (Sandbox Code Playgroud)
在这里设置什么?
如何传递参数?(根据我的知识 - 选择器仅指定要调用的方法)
你需要改为使用+[NSTimer scheduledTimerWithTimeInterval:invocation:repeats:].默认情况下,用于触发计时器的选择器需要一个参数.如果您需要其他内容,则必须创建一个NSInvocation对象,而计时器将使用该对象.
如果你想要使用一组相当复杂的参数来调用方法,我建议将参数捕获到包含配置的东西中,并且可以根据该配置做任何需要做的事情......
像这样的界面的东西:
PositionSetter.h:
@interface PositionSetter : NSObject
{
NSInteger x;
NSInteger y;
Sprite *target;
}
+ positionSetterWithX: (NSInteger) xPos y: (NSInteger) yPos sprite: (Sprite *) aSprite;
- (void) applyPosition;
@end
Run Code Online (Sandbox Code Playgroud)
PositionSetter.m:
@interface PositionSetter()
@property(readwrite, nonatomic) NSInteger x;
@property(readwrite, nonatomic) NSInteger y;
@property(readwrite, nonatomic, retain) Sprite *target;
@end
@implementation PositionSetter
@synthesize x, y, target;
+ positionSetterWithX: (NSInteger) xPos y: (NSInteger) yPos sprite: (Sprite *) aSprite;
{
PositionSetter *positionSetter = [PositionSetter new];
positionSetter.x = xPos;
positionSetter.y = yPos;
positionSetter.target = aSprite;
return [positionSetter autorelease];
}
- (void) applyPosition;
{
[self.target setPosition:CGPointMake(self.x,self.y)];
}
@end
Run Code Online (Sandbox Code Playgroud)
用法很简单:
positionSetter = [PositionSetter positionSetterWithX: 42 y: 21 sprite: mySprite];
[positionSetter performSelector: @selector(applyPosition) withObject: nil afterDelay: 1.0];
Run Code Online (Sandbox Code Playgroud)
虽然代码更多,但最终的实现速度足够快 - 可能比NSInvocation更快,但速度足够快,因为这将导致绘图 - 并且更加灵活.我很容易看到将上述内容重构为驾驶,比如CoreAnimation.
复制自Matt Ball的回答:
- (void)startMyTimer {
/* ... Some stuff ... */
NSDictionary *userDict;
userDict = [NSDictionary dictionaryWithObjectsAndKeys:someValue,
@"value1",
someOtherValue,
@"value2", nil];
[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(callMyMethod:)
userInfo:userDict
repeats:YES];
}
- (void)callMyMethod:(NSTimer *)theTimer {
NSString *value1 = [[theTimer userInfo] objectForKey:@"value1"];
NSString *value2 = [[theTimer userInfo] objectForKey:@"value2"];
[self myMethod:value1 setValue2:value2];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4919 次 |
| 最近记录: |