Aho*_*tbi 4 cocoa-touch objective-c nstimer ios
我创建了一个NSTimer:
[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(createObject:)
userInfo:nil
repeats:YES];
Run Code Online (Sandbox Code Playgroud)
并createObject:定义如下:
- (void)createObject:(ccTime) dt{
int r = arc4random() % 4;
for (int i=0; i < r; i++) {
character[charIndex] = [CCSprite spriteWithFile:@"o.png"];
}
}
Run Code Online (Sandbox Code Playgroud)
我想要实现的是将一些变量发送到方法中.我重写了这个函数:
- (void)createObject:(ccTime) dt cID:(int)cID {
int r = arc4random() % 4;
for (int i=0; i < r; i++) {
character[cID] = [CCSprite spriteWithFile:@"o.png"];
}
}
Run Code Online (Sandbox Code Playgroud)
但我无法将变量传递cID给定时器中的函数.是否有可能做到这一点?
Mat*_*uch 17
根据从NSTimer调用的文档方法需要这样的签名:
- (void)timerFireMethod:(NSTimer*)theTimer
Run Code Online (Sandbox Code Playgroud)
无法提供自定义参数或多个参数.
因此,重写您的计时器方法,以便它使用NSTimer的userInfo
- (void)createObject:(NSTimer *)timer {
NSDictionary *userInfo = [timer userInfo];
int cID = [[userInfo objectForKey:@"cID"] intValue];
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
创建一个userInfo,然后像这样启动计时器:
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:cID], @"cID",
/* ... */
nil];
[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(createObject:)
userInfo:userInfo
repeats:YES];
Run Code Online (Sandbox Code Playgroud)
您的选择器必须具有以下签名:
- (void)timerFireMethod:(NSTimer*)theTimer
Run Code Online (Sandbox Code Playgroud)
但是Cocoa中有UserInfo的概念
userInfo:
计时器的用户信息.您指定的对象由计时器保留,并在计时器失效时释放.此参数可能为零.
因此,清楚地说,您可以使用它将信息传递给定时器调用的方法,并且从该方法可以访问UserInfo.
information = [theTimer userInfo];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6919 次 |
| 最近记录: |