透過userInfo:就可以了,它可以傳遞任何的物件,那麼把你要傳過去的參數包成物件即可。
例子:
傳遞字串給sayHi:方法
NSTimer *mytimer;
NSString *name = @"Tom";
mytimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self selector:@selector(sayHi:) userInfo:name repeats:NO]; |
要注意,接收端要NSTimer形態↓
-(void)sayHi:(NSTimer *)timer{
NSString *name = timer.userInfo;
NSLog(@"HI %@",name);
}
|
如果要傳遞多個資料,可以將多個物用NSMutableDictionary包起來
NSTimer *mytimer;
NSString *name = @"Tom";
//創建一個NSString物件
NSNumber *intNumber = [[NSNumber alloc] initWithInt:100];
//創建一個NSNumber物件
NSArray *array = [NSArray new];
//創建一個NSArray
NSMutableDictionary *d = [NSMutableDictionary dictionary];
[d setObject:name forKey:@"name"];
[d setObject:intNumber forKey:@"number"];
[d setObject:array forKey:@"array"];
//創建NSMutableDictionary物件並將以上物件包入
mytimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sayHi:) userInfo:d repeats:NO];
|
傳遞過去後在轉回NSMutableDictionary,利用objectForKey轉回原本的物件
-(void)sayHi:(NSTimer *)timer{
NSMutableDictionary *d = timer.userInfo;
NSString *name = [d objectForKey:@"name"];
NSLog(@"%@",name);
}
|
沒有留言:
張貼留言