Я хочу сделать приложение, где вы получаете 1 балл каждую секунду, и все работает отлично. Но поскольку у меня есть несколько контроллеров просмотра, таймер снова запускается и дает 2 очка в секунду. Как я могу это исправить?Swift - Как я могу загрузить функцию только один раз?
Код:
//
// ViewController.swift
// TapTap
//
// Created by Jonas Boutrup on 10/02/2016.
// Copyright © 2016 Jonas Boutrup. All rights reserved.
//
import UIKit
import RealmSwift
import Foundation
class ViewController: UIViewController {
//initialize your realm
let realm = try! Realm()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.darkGrayColor()
loadpoints()
startAddPoints()
print(Realm.Configuration.defaultConfiguration.path!)
}
@IBOutlet weak var pointLabel: UILabel!
@IBOutlet weak var bonusPointLabel: UILabel!
var points = 0
var bonusPoints = 0
var multiplierClick = 0
var pointsPerSecond = 1
var timer = NSTimer()
func loadpoints() {
//check if there is a Click with id == 1
if let clickWithId1 = realm.objects(Click).filter("id == 1").first {
self.points = clickWithId1.totalPoints
self.bonusPoints = clickWithId1.totalBonusPoints
self.multiplierClick = clickWithId1.multiplierClick
self.pointsPerSecond = clickWithId1.pointsPerSecond
} else { // if there is no Click with id == 1, create it and add it to realm
let click = Click()
click.id = 1
click.totalBonusPoints = 0
click.totalPoints = 0
click.multiplierClick = 1
click.timesTwoPrice = 20
click.pointsPerSecond = 1
self.points = click.totalPoints
self.bonusPoints = click.totalBonusPoints
do {
try realm.write {
realm.add(click, update: true)
}
} catch {}
}
self.pointLabel.text = "\(points)"
self.bonusPointLabel.text = "\(bonusPoints)"
}
func startAddPoints() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("addPoints"), userInfo: nil, repeats: true)
}
func addPoints() {
//check if there is a Click with id == 1
if let clickWithId1 = realm.objects(Click).filter("id == 1").first {
do {
//if there is a Click with id == 1, increment its totalclicks by 1 and update it
try realm.write {
clickWithId1.totalPoints += clickWithId1.pointsPerSecond
realm.add(clickWithId1, update: true)
}
} catch {}
loadpoints()
}
}
@IBAction func buttonTapped(sender: AnyObject) {
//check if there is a Click with id == 1
if let clickWithId1 = realm.objects(Click).filter("id == 1").first {
do {
//if there is a Click with id == 1, increment its totalclicks by 1 and update it
try realm.write {
clickWithId1.totalPoints += clickWithId1.multiplierClick
realm.add(clickWithId1, update: true)
}
self.points = clickWithId1.totalPoints
self.pointLabel.text = "\(points)"
let roll = arc4random_uniform(100) + 1
print("\(roll)")
if roll == 14 {
try realm.write {
clickWithId1.totalBonusPoints += 1
self.bonusPoints = clickWithId1.totalBonusPoints
self.bonusPointLabel.text = "\(bonusPoints)"
realm.add(clickWithId1, update: true)
}
}
} catch {}
}
}
}
Заранее спасибо! : D
EDIT
Я нашел решение для этого! У вас должна быть кнопка, которая останавливает таймер!
@IBAction func stopTimer(sender: AnyObject) {
timer.invalidate()
}
См. [Как создать минимальный, завершенный и проверяемый пример] (http://stackoverflow.com/help/mcve) в Справочном центре. – tktsubota