【发布时间】:2014-10-22 19:54:32
【问题描述】:
我有一个应用程序来管理一个简单的股票投资组合。除其他外,它在字典中记录所需的汇率,如下所示: [欧元美元=X:1.267548] 这个字典是一个名为 CurrencyRateStore 的单例的字典属性。
更新股票报价时,它会检查更新的汇率并使用以下代码更新字典:
CurrencyRateStore.sharedStore()[symbol] = fetchedRate.doubleValue
那叫:
subscript(index: String) -> Double? {
get {
return dictionary[index]
}
set {
// FIXME: crashes when getting out of the app (Home button) and then relaunching it
dictionary[index] = newValue!
println("CurrencyRateStore - updated rate for \(index) : \(newValue!)")
}
}
应用程序第一次启动时,它运行良好。 但是如果我退出应用程序(使用主页按钮)然后重新启动它,货币汇率会再次更新,但这一次,我在线路上得到一个 EXC_BAD_ACCESS
dictionary[index] = newValue!
这是一个截图:
[编辑] 这是调试导航器中的线程:
我尝试在没有下标的情况下更新字典,如下所示:
CurrencyRateStore.sharedStore().dictionary[symbol] = fetchedRate.doubleValue
但没有更多的成功。如果我使用函数 updateValue:forKey: 我在 Objective-C 中没有这个问题。
感谢您的帮助!
[编辑] 这是整个类CurrencyRateStore:
class CurrencyRateStore {
// MARK: Singleton
class func sharedStore() -> CurrencyRateStore! {
struct Static {
static var instance: CurrencyRateStore?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = CurrencyRateStore()
}
return Static.instance!
}
// MARK: Properties
/** Dictionary of currency rates used by the portfolio, presented like [ EURUSD=X : 1.3624 ] */
var dictionary = [String : Double]()
/** Returns a sorted array of all the keys on the currency rates dictionary */
var allKeys: [String] {
var keysArray = Array(dictionary.keys)
keysArray.sort {$0 < $1}
return keysArray
}
init() {
if let currencyRateDictionary: AnyObject = NSKeyedUnarchiver.unarchiveObjectWithFile(currencyRateArchivePath) {
dictionary = currencyRateDictionary as [String : Double]
}
}
subscript(index: String) -> Double? {
get {
return dictionary[index]
}
set {
// FIXME: crashes when getting out of the app (Home button) and then relaunching it
// (ApplicationWillEnterForeground triggers updateStocks)
dictionary[index] = newValue!
println("CurrencyRateStore - updated rate for \(index) : \(newValue!)")
}
}
func deleteRateForKey(key: String) {
dictionary.removeValueForKey(key)
}
/** Removes all currency rates from the Currency rate store */
func deleteAllRates()
{
dictionary.removeAll()
}
// MARK: Archive items in CurrencyRateStore
var currencyRateArchivePath: String { // Archive path
var documentDirectories: Array = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
// Get the only document directory from that list
let documentDirectory: AnyObject = documentDirectories.first!
return documentDirectory.stringByAppendingPathComponent("currencyRates.archive")
}
func saveChanges()-> Bool
{
// return success or failure
return NSKeyedArchiver.archiveRootObject(dictionary, toFile: currencyRateArchivePath)
}
}
【问题讨论】:
-
你能发布整个错误日志吗?也许这可以帮助
-
能否也分享
CurrencyRateStore的一些相关部分?至少是单例实现,字典属性的声明 -
但是 EXC_BAD_ACCESS 上没有日志……你的意思是,调试导航器中的线程?
-
如果你在模拟器中运行,检查
~/Library/Logs/DiagnosticReports/文件夹 -
在模拟器中,它可以工作......只有在真正的 iPhone 6 上运行时才会崩溃......等等,我会尝试从设备中删除该应用程序,然后重新安装。
标签: swift dictionary ios8