【问题标题】:Arguments with NSTimersNSTimers 的参数
【发布时间】:2011-12-03 16:39:20
【问题描述】:

是否可以在设置 NSTimer 时在方法中给出参数?我想创建如下内容:

[NSTimer [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(moveParticle:imageView) userInfo:nil repeats:YES];

其中“imageView”是方法的参数。它给了我一个错误,说它在“imageView”之后的parathesis之后需要一个分号。

有什么帮助吗?

【问题讨论】:

标签: iphone objective-c xcode nstimer


【解决方案1】:

您想使用 userInfo 来发送参数。查看有关如何使用它的文档。您只需让您的函数采用单个 NSTimer 参数,然后计时器将自行返回,您可以读取它的 userInfo 字典。

【讨论】:

  • 我认为这不是一个好主意。 userinfo 对象由计时器本身保留和释放。
  • 这正是 userInfo 的用途。
  • 对不起,你是对的。 NSInvocation 只有在你真的想要很大的灵活性时才应该使用。
【解决方案2】:

这就是 userInfo 参数的用途。您可以将 imageView 作为 userInfo 传递,并在您作为选择器提供的方法中将其转换为所需的类型(NSView?)。 例如:

- (void)moveParticle:(NSTimer*)theTimer
{
    NSView* imageView = (NSView*)[theTimer userInfo);
    ...
}

另一种方法(在这里可能更有用 - 因为您的目标是 self),将 imageView 设为 iVar 并在 moveParticle 中访问它。

【讨论】:

  • 问题是屏幕上会有随机数量的星星。也许是带有图像视图名称的 NSMutableArray?
【解决方案3】:

duplicate thread

您需要改用+[NSTimer scheduledTimerWithTimeInterval:invocation:repeats:]。默认情况下,用于触发计时器的选择器采用一个参数。如果您需要除此之外的其他内容,则必须创建一个 NSInvocation 对象,计时器将使用该对象。

一个例子:

NSMethodSignature * mSig = [NSMutableArray instanceMethodSignatureForSelector:@selector(moveParticle:)];
NSInvocation * myInvocation = [NSInvocation invocationWithMethodSignature:mSig];
[myInvocation setTarget:myArray];
[myInvocation setSelector:@selector(moveParticle:)];
[myInvocation setArgument:&imageView atIndex:2]; // Index 2 because first two arguments are hidden arguments (self and _cmd). The argument has to be a pointer, so don't forget the ampersand!
NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 invocation:myInvocation repeats:true];

【讨论】:

    猜你喜欢
    • 2012-04-22
    • 1970-01-01
    • 2011-07-07
    • 2012-02-15
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    相关资源
    最近更新 更多