在Swift中将变量从前景传递到背景 [英] Pass a variable from foreground to background in Swift

查看:74
本文介绍了在Swift中将变量从前景传递到背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个iOS应用程序,我想在其中记录用户按下特定按钮并保持它的时间.稍后,我将在后台使用此时间记录.有没有不调用NSUserDefaults或CoreData或任何其他数据库的好方法吗?

I am developing an iOS application where I want to record the time when a user presses a particular button and keep it. Later I will use this time record in background. Is there a nice way of doing that without invoking NSUserDefaults or CoreData or whatever other database?

我对iOS开发非常陌生.我认为这很可能是一个幼稚的问题.但是我很好奇.请不要嘲笑我哈哈.

I am very new to iOS development. I think this is very likely to be a naive question. But I'm just curious. Please don't laugh at me haha.

这确实是一个非常幼稚的问题哈哈.

This is indeed a very naive question haha.

推荐答案

一种简单的方法来确保数据在应用程序中的任何地方都可用,并且仅在每个应用程序会话中都持久存在,这是使用单例. 这样的事情.

A simple way to make sure your data is available everywhere in your app and only persists for each app session would be to use a singleton. Something like this.

// Create a class to store the data
class SessionData : NSObject {

    // Create a shared instance of your class
    static let sharedInstance = SessionData()

    // Create a variable to store the date object
    var timeStore:NSDate?
}

这意味着您可以在应用中的任何位置getset如下所示

This will mean that anywhere in your app you can get and set this data as below.

// Get
if let time = SessionData.sharedInstance.timeStore {
    println(time)
}

// Set
SessionData.sharedInstance.timeStore = NSDate()


值得一提的是,尽管以上方法是有效的,但您可以通过重新考虑应用程序结构并在类之间传递数据来避免这样做.您应该看看在委派.


It is worth mentioning that despite the above being a valid method, You may be able to avoid doing this by re-thinking your app structure and passing data between classes instead. You should have a look at Delegation.

正如@CouchDeveloper在下面的评论中提到的那样,您可能希望包括一个调度队列,以防止在两个或多个类尝试同时读取和/或写入数据的情况下发生崩溃或锁定./em>

Also as @CouchDeveloper mentions in their comment below, you may want to included a dispatch queue to prevent crashes or locks in the situation where two or more classes try to read and or write data at the same time.

这篇关于在Swift中将变量从前景传递到背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆