Reputation: 209
in this scenario, what difference in this code :
OBJ-C :
- (void)viewDidLoad {
[super viewDidLoad];
NSTimer *myTimer = [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(start) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:myTimer forMode:NSDefaultRunLoopMode];
[self start];
}
in Obj-C this code work smoothly, and i use similar code using Swift like this :
override func viewDidLoad() {
super.viewDidLoad()
var myTimer = NSTimer(timeInterval: 5.0, target: self, selector: Selector(start()), userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(myTimer, forMode: NSDefaultRunLoopMode)
start()
}
but have error after 5 sec, and no clue what error exactly, just EXC_BAD_ACCESS(code= 1, address=0x0)
what am i missing?
Upvotes: 1
Views: 261
Reputation: 1
- (void)setupTimer {
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(onTick:)
userInfo:nil
repeats:NO];
}
- (void)onTick:(NSTimer *)timer {
// Put your code here
}
Upvotes: 0
Reputation: 285250
Nowadays (Swift 3+) use always native Timer
, the scheduledTimer
API and – whenever possible – the block based API
override func viewDidLoad() {
super.viewDidLoad()
let myTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { timer in
// do something
}
}
And if you are using the target / action based API use Swift #selector
syntax and put the action method out of viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
let myTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(start), userInfo: nil, repeats: true)
}
@objc func start(_ timer: Timer) {
// do something
}
Upvotes: 0
Reputation: 1390
let myTimer = NSTimer(timeInterval: 5.0, target: self, selector: "start", userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(myTimer, forMode: NSDefaultRunLoopMode)
func start() {
print("Fired")
}
Upvotes: 2