У меня есть приложение, управляющее простым портфелем акций. Помимо всего прочего, он ведет учет требуемых обменных курсов в словаре, например: [EURUSD = X: 1.267548] Это свойство является одним из свойств словаря под названием CurrencyRateStore.Swift - доступ к словарю Singleton вызывает EXC_BAD_ACCESS
При обновлении штоков котировки, он проверяет наличие обновленного курса и обновляет словарь со следующим кодом:
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!)")
}
}
В первый раз приложение запускается , он отлично работает. Но если я выйти из приложения (с помощью кнопки Home), а затем возобновить его, курсы валют обновляются снова, но на этот раз, я получаю EXC_BAD_ACCESS на линии
dictionary[index] = newValue!
Вот скриншот:
[EDIT] Вот нить в отладочный навигатора:
Я пытался обновить словарь без индекса, например, так:
CurrencyRateStore.sharedStore().dictionary[symbol] = fetchedRate.doubleValue
но без особого успеха. То же самое, если я использую функцию updateValue: forKey: У меня не было проблемы в Objective-C.
Спасибо за помощь!
[EDIT] Вот весь класс 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)
}
}
не могли бы вы опубликовать всю ошибку войти? может быть, может помочь – Antonio
вы могли бы также поделиться некоторыми соответствующие части 'CurrencyRateStore'? по крайней мере одноплодной реализации, декларирование словаря собственности – Antonio
Но нет журнала на EXC_BAD_ACCESS ... То есть, поток в навигаторе отладки? –