mjr
mjr

Reputation: 807

Object is nil only in dictionary

If I declare and set a variable at the top of a class, like

class Test {
    var timer = NSTimer()
    ...

and test its validity in a function later, like if timer.valid {...}, no problem. But if I put it in a dictionary

var timers = ["first": NSTimer(), ...]

and test that with if timers["first"]!.valid {...}, I get an "unexpectedly found nil" fatal error at runtime. Why are these behaviors different, and how can I get the dictionary not to throw out my timer initialization? If this is a duplicate please point it out, I just don't really know what to search for. The Dictionary docs didn't shed any light, and I haven't tried it with anything but NSTimer.

Upvotes: 0

Views: 82

Answers (3)

paulvs
paulvs

Reputation: 12053

From the NSObject docs about the init() initializer:

Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.

Later:

An object isn’t ready to be used until it has been initialized.

According to the NSTimer docs, init() is not listed as a valid initializer for creating a timer.

Upvotes: 1

Ryan Jin
Ryan Jin

Reputation: 119

Unlike int, string, and other data types, which in you initialize by saying int() or String(). You cannot simply do NSTimer(). It crashes when you try to do that, so you always get a nil. If you want a timer, try

NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval, target: AnyObject, selector: Selector, userInfo: AnyObject?, repeats: Bool)

Just fill in the time interval, target, selector, user info, and repeats.

Upvotes: 1

Rob Napier
Rob Napier

Reputation: 299355

This is a bug in Foundation and you should open a defect. NSTimer() is not a valid initializer and it should be marked as unavailable. A similar thing occurs with NSError by the way. Swift lets you construct them with NSError() even though they are then invalid and will crash if you try to use them.

The fact that you happen to get away with it, and it likely is returning "false" due to nil-messaging (which is how ObjC works), shouldn't be seen as "it should work." NSTimer() is invalid code.

Upvotes: 5

Related Questions