Starting countdown in update func - ios

I want to start a countdown after I add a sprite to make sure other sprites will add/ functions will be called after a certain amount of time. So far I have made sure the variable countdownCanStart will change from false to true as I add my sprite.
Inside the touchesBegan function:
//adding the sprite by touch
addSprite()
if spriteAdded {
countdownCanStart = true
}
Then in the update func:
override func update(currentTime: NSTimeInterval) {
if countdownCanStart {
var framecount = 0
framecount++
if framecount == 10 {
AddTheOtherSprites()
}
}
}
The code runs, it doesn't crash, but next to the row AddTheOtherSprites() I see a yellow warning sign: "Will never be executed"

In your update function, you are declaring a fresh variable framecount and initializing it to 0. Then incrementing it, then checking if it’s equal to 10. It never will be - every time you run update, a new framecount variable will be declared and it will only ever be of value 1 when it’s tested against 10 in the if statement.

You're creating framecount within your update method, therefore a new framecount is created every time update begins and destroyed when update ends. Because of this the maximum framecount will ever reach is 1 (from framecount++) and so framecount == 10 always returns false. To solve this, place framecount outside your update method.

This warning is due to framecount being a local scoped var (in regards to the update method) ,so every time the update method will be called framecount will be initialized with 0 and incremented by 1 so it will never be equal to 10.
Change the scope of framecount to be outside the update method

Related

swift smooth (interpolate) between incoming continuous data

Working in Swift I have a function which is called on arrival of new data (Double between 0 and 1). I need this function to go smoothly to the next value. In another language (MaxMSP) I could simply say go in 20 milliseconds from the previous value to the new one, this would even work if new data arrived before the set time was over. How could I achieve this in Swift? I've found vDSP.convolve() but I'd need an array of values to interpolate between, in my case data is real time and I have the latest value and previous value(s). The code I have is
var previousValue: Double = 0
var value: Double = 0 {
didSet {
valueDidChange()
}
}
private func valueDidChange() {
let valueSmooth = value * //smoothing magic with previousValue
}

If variable is not set, wait for variable to be set

I have 2 delegate methods that are being called by notifications from a 3rd party library.
Method 1:
mediaContentWasUpdated()
Method 2:
adMediaDidBeginPlaying()
In Method 1, a key variable (adDuration) is set from a parameter that is passed in with the notification. As far as I can see this is the only place to get this information.
In Method 2, we check the adDuration and if it is greater than 0 then we update the UI to reflect that we are in fact play an ad.
A bug has appeared where sometimes these two methods are called in the wrong order. Meaning the adDuration is not set and Method 2 thinks there is no ad media to be played and does not update the UI accordingly.
My current attempt at a solution is to make adDuration optional and use an NSCondition to cause Method 2 to wait for Method 1 to set adDuration and then proceed.
var adDuration : Double?
let condition = NSCondition()
func mediaContentWasUpdated(notification: NSNotificiation) {
condition.lock()
if(notificationHasAdDurationInfo(notification)) {
self.adDuration = getAdDuration(notification)
condition.signal()
}
condition.unlock()
}
func adMediaDidBeginPlaying(notification: NSNotification) {
condition.lock()
while adDuration == nil {
condition.wait()
}
if adDuration! > Double(0) {
updateUIForAd()
}
condition.unlock()
}
This is my first time trying something like this and I worry I am doing something wrong. I also have some concerns about locking and unlocking threads needlessly (which would happen in a well timed run, or if there were no ad content to be played).
Outside factors are hindering my ability to test and I wanted to get some input to see if I am heading in the right direction while I wait for those issues to be resolved.
Your discussion of NSCondition got me on the same track with you, and I built two or three solutions using DispatchGroup (which is the better tool for this), but they always had little corner cases that could behave badly, and didn't really capture the intent.
(If you're interested in the DispatchGroup solutions, they're of the form: call .enter() in init, call .leave() when the duration comes in, call notify() when the playing starts. It works fine, but it introduces corner cases that can crash, just like NSCondition.)
Getting back to the real intent:
Update the UI when the duration is known and the ad has started playing.
There's no concurrency going on here. So pulling out GCD is not just overkill; it actually makes things worse because it introduces lots of complicated corner cases.
So I thought about how I'd have solved this back before GCD. And the answer is obvious: just check if you have the data you want, and then do the thing. (Reading through the comments, I see Paulw11 pointed this out as well.)
Personally I like to pull this kind of thing into its own type to make things more self-contained. I hate some of the names here, but the idea should be clear:
class AdPlayer {
private var readyToPlay = false
private var duration: Double = 0.0
private let completion: (Double) -> Void
func setDuration(from notification: Notification) {
if(notificationHasAdDurationInfo(notification)) {
duration = getAdDuration(notification)
}
playIfReady()
}
func play() {
readyToPlay = true
playIfReady()
}
private func playIfReady() {
if duration > 0 && readyToPlay {
completion(duration)
}
}
init(completion: #escaping (Double) -> Void) {
self.completion = completion
}
}
When you set each thing, see if you're ready to update, and if so, update. I've gotten rid of the optional as well, since I believe the intent is "0 duration is always wrong." But you could use an Optional so you could detect actually receiving a 0 from the notification.
With that, you just set up a player property:
player = AdPlayer(completion: updateUIForAd)
(Note that the above might be creating a retain loop, depending on what updateUIForAd is; you may need a [weak self] closure or the like here.)
And then update it as needed:
func mediaContentWasUpdated(notification: NSNotificiation) {
player.setDuration(from: notification)
}
func adMediaDidBeginPlaying(notification: NSNotification) {
player.play()
}
A big advantage of creating the AdPlayer type is that it's easy to reset the system when the ad is done (or if something goes wrong). Just throw away the whole object and create another one.

Xcode 8/Swift 3: Reset all variables to initial values

When a gameOver() function is triggered, I would like all variables to reset to their original, unchanged values (as in, the values that are assigned in the ViewController file) when a user presses a Restart button. How can I do this?
Depending on the specific variables you have, one solution would be to create a struct with the fixed initial values and assign those to your active game variables in the Restart function.
You can define a function that reset the variables to the default value like this :
func resetGame(){
score = 0 // or default value
life = 3 // or default value
//.... and so on
}
Assume the restart button are connected to this function
#IBAction func restartGame(sender: UIButton){
gameOver()
resetGame()
}
you can call this function after calling gameOver() inside the restart button function.
If your question is about how to declare default values you can use struct as Jay said like this :
struct DefaultValues {
let score = 0
let lifes = 3
let level = 1
}
and resetGame() will be like this :
func resetGame(){
score = DefaultValues().score
life = DefaultValues().life
level = DefaultValues().devel
}

Why increment inside function isn't working?

I try to make function run only one time during runtime, but it fires every time instead
var requestCount: Int = 0
func JSONRequest() {
if self.requestCount == 0 {
...some stuff
self.requestCount = requestCount + 1
} else {
println("JSONRequest dismissed")
}
During debugging I figured out that every time JSONRequest() runs it has value of self.requestCount equal to zero. For some reason it doesn't save increment and every time i call the function the self.requestCount is 0.
Why ? What am I doing wrong ?
Could it be that your code is in a ViewController which is being re-created each time (and therefore the count is re-initialized to zero each time)?
If so, you can do one of the following:
use a singleton - not always the cleanest but it works
use persistence (e.g., CoreData or NSUserDefaults)

What is difference between self.timer = nil vs [self.timer invalidate] in iOS?

Can anyone explain me self.timer=nil vs [self.timer invalidate]?
What exactly happens at the memory location of self.timer?
In my code
self.timer=nil
doesn't stops the timer but
[self.timer invalidate]
stops the timer.
If you require my code I will update that too.
Once you have no need to run timer, invalidate timer object, after that no need to nullify its reference.
This is what Apple documentation says: NSTimer
Once scheduled on a run loop, the timer fires at the specified
interval until it is invalidated. A non-repeating timer invalidates
itself immediately after it fires. However, for a repeating timer, you
must invalidate the timer object yourself by calling its invalidate
method. Calling this method requests the removal of the timer from the
current run loop; as a result, you should always call the invalidate
method from the same thread on which the timer was installed.
Invalidating the timer immediately disables it so that it no longer
affects the run loop. The run loop then removes the timer (and the
strong reference it had to the timer), either just before the
invalidate method returns or at some later point. Once invalidated,
timer objects cannot be reused.
There is a key difference not mentioned in the other answers.
To test this, drop the following code in Playground.
1st Attempt:
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
class Person{
var age = 0
lazy var timer: Timer? = {
let _timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)
return _timer
}()
init(age: Int) {
self.age = age
}
#objc func fireTimer(){
age += 1
print("age: \(age)")
}
deinit {
print("person was deallocated")
}
}
// attempt:
var person : Person? = Person(age: 0)
let _ = person?.timer
person = nil
So let me ask you a question. At the last line of the code, I just set person to nil. That means the person object is deallocated and all its properties are set to nil and removed from memory. Right?
An object is deallocated as long as no other object is holding a strong a reference to it. In our case the timer is still holding a strong reference to person, because the run-loop has a strong reference to the timer§ hence the person object will not get deallocated.
The result of the above code is that it still continues to execute!
Let's fix it.
2nd Attempt:
Let's set the timer to nil. This should remove the strong reference of timer pointing to person.
var person : Person? = Person(age: 0)
let _ = person?.timer
person?.timer = nil
person = nil
WRONG! We only removed our pointer to the timer. Yet the result of the above code is just like our initial attempt. It still continues to execute...because the run loop is still targeting/referencing self.
So what do we need to do?
Glad you asked. We must invalidate the timer!
3rd Attempt:
var person : Person? = Person(age: 0)
let _ = person?.timer
person?.timer = nil
person?.timer?.invalidate()
person = nil
This looks better, but it's still wrong. Can you guess why?
I'll give you a hint. See code below 👇.
4th Attempt (correct)
var person : Person? = Person(age: 0)
let _ = person?.timer
person?.timer?.invalidate()
person?.timer = nil
person = nil
// person was deallocated
Our 4th attempt was just like our 3rd attempt, just that the sequence of code was different.
person?.timer?.invalidate() removes the run loop's strong reference
to its target, i.e. self, and now if a pointer to person is removed...our person object gets deallocated!
The attempt below is also correct:
5th Attempt (correct)
var person : Person? = Person(age: 0)
let _ = person?.timer
person?.timer?.invalidate()
person = nil
// person was deallocated
Notice that in our 5th attempt we didn't set the timer to nil. But Apple recommends that we do such:
Once invalidated, timer objects cannot be reused.
See Task Management - Timer
Setting it to nil is also an indicator that for other parts of code. It helps up so that we can check against it and if it wasn't nil then we'd know the timer is still valid and also to not have a meaningless object around.
After invalidating the timer you should assign nil to the variable
otherwise the variable is left pointing to a useless timer. Memory
management and ARC have nothing to do with why you should set it to
nil. After invalidating the timer, self.timer is now referencing a
useless timer. No further attempts should be made to use that value. Setting it to nil ensures that any further attempts to access
self.timer will result in nil
from rmaddy's comment above
That being said I think isValid is a more meaningful approach just as isEmpty is more meaningful and efficient than doing array.count == 0...
So why is 3rd attempt not correct?
Because we need a pointer to the timer so we can invalidate it. If we set that pointer to nil then we loose our pointer to it. We lose it while the run-loop has still maintained its pointer to it! So if we ever wanted to turn off the timer we should invalidate it BEFORE we lose our reference to it (ie before we set its pointer to nil) otherwise it becomes an abandoned memory (not leak).
Conclusion:
To get stop a timer correctly you must use invalidate. Do not nil the timer before you invalidate it.
After you've invalidated a timer, set it to nil so it doesn't get reused.
Calling invalidate will remove the run loop's pointer to self. Only then the object containing the timer will be released.
So how does this apply when I'm actually building an application?
If your viewController has person property and then your popped this viewController off your navigation stack then your viewController will get deallocated. In its deinit method you must invalidate the person's timer. Otherwise your person instance is kept in memory because of the run loop and its timer action will still want to execute! This can lead to a crash!
Correction:
Thanks to Rob's answer
If you're dealing with repeating [NS]Timers, don't try to invalidate them in dealloc of the owner of the [NS]Timer because the dealloc obviously will not be called until the strong reference cycle is resolved. In the case of a UIViewController, for example, you might do it in viewDidDisappear
That being said viewDidDisappear may not always be the correct place since viewDidDisappear also gets called if you just push a new viewController on top of it. You should basically do it from a point that it's no longer needed. You get the idea...
§: Because the run loop maintains the timer, from the perspective of
object lifetimes there’s typically no need to keep a reference to a
timer after you’ve scheduled it. (Because the timer is passed as an
argument when you specify its method as a selector, you can invalidate
a repeating timer when appropriate within that method.) In many
situations, however, you also want the option of invalidating the
timer—perhaps even before it starts. In this case, you do need to
keep a reference to the timer, so that you can stop it whenever
appropriate.
With all the credit going to my colleague Brandon:
Pro Tip:
Even if you don't have a repeating timer, the Runloop [as mentioned within the docs] will hold a strong reference to your target if you use the selector function, until it fires, after that it will release it.
However if you use the block based function then as long as you point weakly to self inside your block then the runloop will not retain self. However it will continue to execute, due to the lack of calling invalidate
If you don't use [weak self] then the block based will act just like the selector kind, that it will deallocate self after it has been fired.
Paste the following code in Playground and see the difference. The selector version will be deallocated after it fires. The block base will be deallocated upon deallocation. Basically the lifecycle of one is governed by the runloop while for the other it's governed by the object itself
#objc class MyClass: NSObject {
var timer: Timer?
func startSelectorTimer() {
timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(MyClass.doThing), userInfo: nil, repeats: false)
}
func startBlockTimer() {
timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: false, block: { [weak self] _ in
self?.doThing()
})
}
#objc func doThing() {
print("Ran timer")
}
deinit {
print("My Class deinited")
}
}
var mySelectorClass: MyClass? = MyClass()
mySelectorClass?.startSelectorTimer()
mySelectorClass = nil // Notice that MyClass.deinit is not called until after Ran Timer happens
print("Should have deinited Selector timer here")
RunLoop.current.run(until: Date().addingTimeInterval(7))
print("---- NEW TEST ----")
var myBlockClass: MyClass? = MyClass()
myBlockClass?.startBlockTimer()
myBlockClass = nil // Notice that MyClass.deinit IS called before the timer finishes. No need for invalidation
print("Should have deinited Block timer here")
RunLoop.current.run(until: Date().addingTimeInterval(7))
First of all, invalidate is a method of NSTimer class which can use to stop currently running timer. Where when you assign nil to any object then, in an ARC environment the variable will release the object.
Its important to stop running timer when you don't longer need, so we write [timer invalidate] and then we write timer = nil; to make sure it'll loose its address from memory and later time you can recreate the timer.

Resources