Swift - 如何只加载一次函数?

时间:2016-02-14 16:53:16

标签: ios xcode swift function timer

我想制作一个应用程序,你每秒得到1分,一切正常。但由于我有多个视图控制器,然后计时器再次运行,并且每秒给出2个点。我该如何解决这个问题?

代码:

#include <string.h>
#include <vector>

class CFakeMutex 
{
public:

    CFakeMutex() 
    {
        printf("CFakeMutex Constructor\n");
    }

    ~CFakeMutex()
    {
        printf("CFakeMutex Destructor\n");
    }
};


class CSimpleString 
{
public:

    CSimpleString() {
        printf("CSimpleString Empty Constructor\n");
    }

    CSimpleString(const char* pString) : m_String(pString) {
        printf("CSimpleString Raw Constructor (%s)\n", pString);
    }

    CSimpleString(const CSimpleString& String) : m_String(String.m_String) {
        printf("CSimpleString Copy Constructor (%s)\n", String.m_String.c_str());
    }

    ~CSimpleString()
    {
        printf("CSimpleString Destructor (%s)\n", m_String.c_str());
    }


    CSimpleString& operator=(const CSimpleString& Src)
    {
        if (&Src == this) return *this;

        printf("CSimpleString Copy Operator (%s)\n", Src.m_String.c_str());

        m_String = Src.m_String;
        return *this;
    }

    CSimpleString& operator=(const char* pString)
    {
        printf("CSimpleString Copy Raw Operator (%s)\n", pString);

        m_String = pString;
        return *this;
    }

    std::string m_String;

};

CSimpleString g_tmp("g_tmp");



CSimpleString TestFunction()
{
    CFakeMutex Mutex;
    CSimpleString local_tmp("local_tmp");

    //local_tmp = "TestFunction";
    //return local_tmp;

    g_tmp = "TestFunction";
    return g_tmp;

}

int main()
{
    CSimpleString result("result");

    result = TestFunction();

    printf("Result = %s\n", result.m_String.c_str());

    return 0;
}

提前致谢! :d

修改

我找到了解决方案!你需要一个停止计时器的按钮!

//
//  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 {}
        }
    }
}

1 个答案:

答案 0 :(得分:1)

Best只会从一个地方调用计时器(例如,另一个不是VC且可全局访问的类或app delegate)。另一种选择可能是每次离开视图控制器时使计时器无效,因此一次只能运行一个计时器。另一种选择可能是将NSTimer的实例作为参数传递给addPoints函数,以便检查特定的计时器对象。有很多方法,但理想情况下你只有一个计时器。