首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSKeyedUnArchiver崩溃

NSKeyedUnArchiver崩溃
EN

Stack Overflow用户
提问于 2016-11-29 14:40:48
回答 1查看 807关注 0票数 1

我的应用程序代理由于NSException崩溃而崩溃。我使用异常断点工具在NSUnarchiver期间和一个名为ItemStore的文件中找出了它崩溃的位置(在其上面添加了一个注释,在init()中)。请帮我解决这个问题,我已经试过我所有的想法了。

没有异常断点,这是崩溃

代码语言:javascript
复制
2016-11-29 09:46:42.546 Foodie[3100:386241] *** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (Photomania.Item) for key (NS.objects); the class may be defined in source code or a library that is not linked'

当我使用异常断点时,我在ItemStore中下面的星型行上接收到一个异常。

ItemStore.swift:

代码语言:javascript
复制
import Foundation

class ItemStore {

var allItems: [Item] = []
let itemArchiveURL: NSURL = {
    let documentsDirectories =
    NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,
        inDomains: .UserDomainMask)
    let documentDirectory = documentsDirectories.first!
    return documentDirectory.URLByAppendingPathComponent("items.archive")
    }()

init() {

    // here is the crash
    if let archivedItems =
        NSKeyedUnarchiver.unarchiveObjectWithFile(itemArchiveURL.path!) as? [Item] {
            allItems += archivedItems
    }
}

func moveItemAtIndex(fromIndex: Int, toIndex: Int) {
    if fromIndex == toIndex {
        return
    }

    // Get reference to object being moved so you can re-insert it
    let movedItem = allItems[fromIndex]

    // Remove item from array
    allItems.removeAtIndex(fromIndex)

    // Insert item in array at new location
    allItems.insert(movedItem, atIndex: toIndex)
}

func createItem() -> Item {
    let newItem = Item(random: true)

    allItems.append(newItem)

    return newItem
}

func removeItem(item: Item) {
    if let index = allItems.indexOf(item) {
        allItems.removeAtIndex(index)
    }
}

func saveChanges() -> Bool {
    print("Saving items to: \(itemArchiveURL.path!)")
    return NSKeyedArchiver.archiveRootObject(allItems, toFile: itemArchiveURL.path!)
}

}

应用程序代表:

代码语言:javascript
复制
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

// Override point for customization after application launch.

//Create an ImageStore
//let imageStore = ImageStore()
//let itemStore = ItemStore()

//Access the ItemsViewController and set its item store
//let navController = window!.rootViewController as! UINavigationController
//let itemsController = navController.topViewController as! ItemsViewController

//itemsController.itemStore = itemStore
//itemsController.imageStore = imageStore

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let rootController = window?.rootViewController

    if rootController is UITabBarController {
        let firstTabItem = (rootController as! UITabBarController).viewControllers?[0]

        if firstTabItem is UINavigationController {

            let firstController = (firstTabItem as! UINavigationController).viewControllers.first as! ItemsViewController
            firstController.itemStore  = ItemStore()
            firstController.imageStore = ImageStore()
        }
    }
    return true
}

...

}

Photomania.Item:

代码语言:javascript
复制
import UIKit

class Item: NSObject, NSCoding {

var meal: String
var restaurantName: String?
var valueInDollars: Int
let dateCreated: NSDate
let itemKey: String

init(meal: String, restaurantName: String?, valueInDollars: Int) {
    self.meal = meal
    self.restaurantName = restaurantName
    self.valueInDollars = valueInDollars
    self.dateCreated = NSDate()
    self.itemKey = NSUUID().UUIDString
}

convenience init(random: Bool = false) {
    if random {
        let nouns = ["Meal"]
        let places = ["Restaurant"]

        var idx = arc4random_uniform(UInt32(nouns.count))
        let randomNoun = nouns[Int(idx)]

        idx = arc4random_uniform(UInt32(places.count))
        let randomPlace = places[Int(idx)]

        let randomName = "\(randomNoun)"
        let randomValue = Int(arc4random_uniform(100))
        let randomRestaurantName = "\(randomPlace)"

        self.init(meal: randomName,
            restaurantName: randomRestaurantName,
            valueInDollars: randomValue)
    }
    else {
        self.init(meal: "", restaurantName: nil, valueInDollars: 0)
    }
}

    required init(coder aDecoder: NSCoder) {
    meal = aDecoder.decodeObjectForKey("meal") as! String
    dateCreated = aDecoder.decodeObjectForKey("dateCreated") as! NSDate
    itemKey = aDecoder.decodeObjectForKey("itemKey") as! String
    restaurantName = aDecoder.decodeObjectForKey("restaurantName") as! String?

    valueInDollars = aDecoder.decodeIntegerForKey("valueInDollars")

    super.init()
}

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(meal, forKey: "meal")
        aCoder.encodeObject(dateCreated, forKey: "dateCreated")
        aCoder.encodeObject(itemKey, forKey: "itemKey")
        aCoder.encodeObject(restaurantName, forKey: "restaurantName")

        aCoder.encodeInteger(valueInDollars, forKey: "valueInDollars")
    }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-29 15:09:57

您没有显示您的Photomania.Item类/结构,但是它应该符合NSCoding protocol.Take,看看下面的示例:http://mhorga.org/2015/08/25/ios-persistence-with-nscoder-and-nskeyedarchiver.html

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40868630

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档