Swift Cannot Output When Using Nstimer

Swift cannot output when using NSTimer

That is a "normal" behaviour of the stdio library. A file descriptor
can be "buffered", which means that the result of all printf() and
other output operations goes to an internal buffer first. When that
buffer reaches a certain size (e.g. 8KB), its contents is written to the actual
file.

There are three modes: "unbuffered" (all output is written to the file
immediately), "line buffered" (output is collected until a newline
characters is printed),
and "fully buffered".

According to Is stdout line buffered, unbuffered or indeterminate by default?:

Unix convention is that stdin and stdout are line-buffered when associated with a terminal, and fully-buffered (aka block-buffered) otherwise.

This explains why you see the output of each print operation
immediately when the output goes to the terminal, but not when
output is redirected to a file.

With

print("buz")
fflush(stdout)

you can force the output to be written to the file immediately.
Alternatively, you can set standard output into line buffering mode
by calling

setlinebuf(stdout)

before anything is printed.

Why am I getting this error message when I am using NSTimer to run function every x seconds?

Change the method getJson() as follows:

class SomeGoodClassName {
func getJson(timer: NSTimer) {
//Directly use shareData.jsonUrl here to get json data

//... more code
}
}

NSTimer initialization

let jsonLoader = SomeGoodClassName()

override func viewDidLoad() {
super.viewDidLoad()
var timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: jsonLoader, selector: "getJson", userInfo: nil, repeats: true)
}

How can I properly format NStimer in Swift?

It looks like a type error — %d expects an integer but you're passing in a double.

You can just cast the result to an Int and that should work:

let s = String(format: "%02d", Int(count%100))

Error when I try to use NSTimer to change View Controller(EXC_BAD_INSTRUCTION)

There's a clue in the console output in your screenshot.

You're implicitly unwrapping imageView but it is nil. This probably means that there's no image view connected to that outlet.

Can't use NSTimer update UI

I find out the problem, I use KVO observe self.leftTimer, when the timer fire, I set my button.enable = NO, so it can't change the title, and when self.leftTime == 0, my button.enable = YES. My careless. Thanks all.

NSTimer.scheduledTimerWithTimeInterval in Swift Playground

You really should not be using NSTimer these days. It's consumes a lot of resources, causes unnecessary battery drain, and the API lends itself to ugly code.

Use dispatch_after() instead:

dispatch_after(0, dispatch_get_main_queue()) { () -> Void in
for counter in 0...1000 {
var b = counter
}
}

Of course, since the timer will fire after playground does it's stuff you will need an equivalent of timer.fire() to force the code to execute immediately instead of after a 0 second delay. Here's how that works:

let printFrom1To1000 = { () -> Void in
for counter in 0...1000 {
var b = counter
}
}

dispatch_after(0, dispatch_get_main_queue(), printFrom1To1000)

printFrom1To1000()

Simple NSTimer implementation issue

You have 2 problems with your code. As @glenstorey points out in his answer, you need to call the method scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:, not the init method you're calling.

EDIT:

As @DanBeauleu says in his comment to my answer, the call would look like this in Swift:

NSTimer.scheduledTimerWithTimeInterval(
1,
target: self,
selector: "Run:",
userInfo: nil,
repeats: true)

The second problem is your Run method.

You don't want a while loop. That will repeat 10 times in a tiny fraction of a second the first time the timer fires, then invalidate the timer.

Your timer method needs to be changed like this:

func Run(timer : NSTimer) 
{

if counter < 10
{
print(counter)
counter++
}
else
{
timer.invalidate()
}
}

(BTW, by strong convention, method/function names should start with a lower-case letter, so your Run function should be named run instead.)

why NSTimer works just once in swift

If you have this code in completion handler, it is recommended NSTimer is running in the main thread so this could be the reason. You might need something like:

dispatch_async(dispatch_get_main_queue(), {
// Your timer logic here
})

Apple docs say:

Timers work in conjunction with run loops. To use a timer effectively,
you should be aware of how run loops operate—see NSRunLoop.

(NSTimer)

The NSRunLoop class is generally not considered to be thread-safe and
its methods should only be called within the context of the current
thread. You should never try to call the methods of an NSRunLoop
object running in a different thread, as doing so might cause
unexpected results.

(NSRunLoop)

UserInfo in NSTimer not passing correct information - Swift

NSTimer's scheduledTimerWithTimeInterval userInfo parameter is not a standard parameter in the sense that although you can set userInfo to hold AnyObject, you can't simply pass in a parameter as you would with most functions because scheduledTimerWithTimeInterval's selector can only be passed an NSTimer as its one and only parameter. So your secondFunction: must specify an NSTimer as its parameter if you'd like to access the value you have stored within the timer's userInfo, ex:

func firstFunction() {
var timer = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: Selector("secondFunction:"), userInfo: self.data!.getInfo(), repeats: false);
println("Info: \(timer.userInfo)");
}

func secondFunction(timer: NSTimer) {
var value = timer.userInfo as Int
secondFunction(value)
}

// Function added based on your comment about
// also needing a function that accepts ints
func secondFunction(value: Int) {
println("Called with \(value)");
}


Related Topics



Leave a reply



Submit