NSTimer是Foundation框架中的一个类,用于创建定时器对象,可以在指定的时间间隔后执行特定的操作。在iOS/macOS开发中,NSTimer常用于执行周期性任务或延迟执行某些操作。
NSTimer的初始化方法timerWithTimeInterval:target:selector:userInfo:repeats:
中的userInfo
参数可以传递一个对象,但不能直接传递原始数据类型(如int、float等)。这是因为Objective-C的方法调用机制要求参数必须是对象。
int myInt = 42;
float myFloat = 3.14f;
BOOL myBool = YES;
// 创建定时器,使用NSNumber包装原始类型
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0
target:self
selector:@selector(handleTimer:)
userInfo:@{@"intValue": @(myInt),
@"floatValue": @(myFloat),
@"boolValue": @(myBool)}
repeats:YES];
// 处理方法
- (void)handleTimer:(NSTimer *)timer {
NSDictionary *userInfo = timer.userInfo;
int intValue = [userInfo[@"intValue"] intValue];
float floatValue = [userInfo[@"floatValue"] floatValue];
BOOL boolValue = [userInfo[@"boolValue"] boolValue];
// 使用这些值...
}
@interface TimerData : NSObject
@property (nonatomic, assign) int intValue;
@property (nonatomic, assign) float floatValue;
@property (nonatomic, assign) BOOL boolValue;
@end
@implementation TimerData
@end
// 创建并配置自定义对象
TimerData *data = [[TimerData alloc] init];
data.intValue = 42;
data.floatValue = 3.14f;
data.boolValue = YES;
// 创建定时器
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0
target:self
selector:@selector(handleTimer:)
userInfo:data
repeats:YES];
// 处理方法
- (void)handleTimer:(NSTimer *)timer {
TimerData *data = timer.userInfo;
// 使用data.intValue, data.floatValue等...
}
#import <objc/runtime.h>
// 设置关联对象
objc_setAssociatedObject(self, @"myIntKey", @(myInt), OBJC_ASSOCIATION_RETAIN);
// 在定时器回调中获取
- (void)handleTimer:(NSTimer *)timer {
NSNumber *number = objc_getAssociatedObject(self, @"myIntKey");
int value = [number intValue];
// 使用value...
}
weak
引用或合适的invalidate时机来避免内存泄漏。timerWithTimeInterval:repeats:block:
方法,它更现代且支持闭包。// iOS 10+推荐方式
__weak typeof(self) weakSelf = self;
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
// 可以直接在这里使用外部变量
NSLog(@"Using myInt: %d", myInt);
}];
问题:为什么我的定时器回调中获取的参数值是nil或错误的?
可能原因:
解决方案:
没有搜到相关的文章