- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在开发我的第一个 Swift iOS 应用程序,在序列化和保存从服务器获取 JSON 的对象时遇到问题。我正在使用Gloss ,一个轻量级 JSON 解析库,它定义了一个 Decodable 协议(protocol),通过该协议(protocol)可以从 JSON 实例化实例。我的目的是从 JSON
([String : AnyObject]
的类型别名)加载一个东西,首先提取它的 id,然后检查我是否已经有本地存档复制。如果这样做,请取消存档并获取图像。如果没有,则对图像文件发出异步请求。
问题在于 Thing.localArchiveExists(id)
始终返回 false
。事物已成功实例化,但它们总是重新获取图像。我检查了文件系统并确认没有写入存档文件。但是,我没有看到“错误。无法存档”,这表明保存成功。我是否缺少有关如何存档和保存 NSCoder 对象的信息?谢谢!
这是我对 Decodable 协议(protocol)的实现:
// MARK: Decodable protocol
// When a thing is loaded from JSON, we load its image from archive if possible.
required init?(json: JSON) {
guard let id: Int = "id" <~~ json else { return nil}
if Thing.localArchiveExists(id) {
guard let savedThing = NSKeyedUnarchiver.unarchiveObjectWithFile(Thing.archiveFilePath(id)) as? Thing else { return nil }
self.id = savedThing.id
self.name = savedThing.name
self.image = savedThing.image
self.imageUrl = savedThing.imageUrl
super.init()
print("Loaded Thing \(self.name) from archive")
}
else {
guard let name: String = "name" <~~ json else { return nil}
guard let imageUrl: NSURL = "url" <~~ json else { return nil}
self.id = id
self.name = name
self.imageUrl = imageUrl
super.init()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let data = NSData(contentsOfURL: imageUrl)
dispatch_async(dispatch_get_main_queue(), {
self.image = UIImage(data: data!)
guard self.save() else {
print("ERROR. Could not archive")
return
}
print("Loaded Thing \(self.name) from server")
})
}
}
}
以下是 Thing 类的相关部分:
// MARK: Properties
var id: Int?
var name: String
var imageUrl: NSURL?
var image: UIImage?
// MARK: Archiving Paths
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("things")
// MARK: Types
struct PropertyKey {
static let nameKey = "name"
static let imageKey = "image"
static let imageUrlKey = "imageUrl"
static let idKey = "id"
}
// Returns the file URL at which a Thing with the given ID should be saved.
class func archiveFilePath(id: Int) -> String {
return Thing.ArchiveURL.URLByAppendingPathComponent("thing\(id)").absoluteString
}
// Checks whether an archived copy of a Thing with the given ID exists.
class func localArchiveExists(id: Int) -> Bool {
let fileManager = NSFileManager.defaultManager()
return fileManager.fileExistsAtPath(Thing.archiveFilePath(id))
}
// MARK: NSCoding
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(name, forKey: PropertyKey.nameKey)
if image != nil {
coder.encodeObject(image!, forKey: PropertyKey.imageKey)
}
if imageUrl != nil {
coder.encodeObject(imageUrl!, forKey: PropertyKey.imageUrlKey)
}
coder.encodeInteger(id!, forKey: PropertyKey.idKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String
let image = aDecoder.decodeObjectForKey(PropertyKey.imageKey) as? UIImage
let imageUrl = aDecoder.decodeObjectForKey(PropertyKey.imageUrlKey) as? NSURL
let id = aDecoder.decodeIntegerForKey(PropertyKey.idKey)
// Must call designated initializer.
self.init(name: name, image: image, imageUrl: imageUrl, id: id)
}
func save() -> Bool {
// For some reason I can't archive to file.
return NSKeyedArchiver.archiveRootObject(self, toFile: Thing.archiveFilePath(self.id!))
}
最佳答案
我发现了我的问题:保存失败,因为我还没有创建我试图保存我的东西的目录。
func save() -> Bool {
let archivedData = NSKeyedArchiver.archivedDataWithRootObject(self)
do {
try NSFileManager.defaultManager().createDirectoryAtURL(Thing.ArchiveURL, withIntermediateDirectories: true, attributes: [:])
try archivedData.writeToFile(Thing.archiveFilePath(self.id!), options: [])
return true
} catch {
print(error)
return false
}
}
关于ios - 尝试归档符合 NSCoder 的类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37283046/
我正在尝试通过 SymSpell 实现自动更正 我已经在容器应用程序中创建了字典,应该保存它并从键盘扩展读取它 字典中包含一个dictionaryItem对象,需要序列化才能被NSCoder保存 我试
我正在 Swift 中实现一个 Circle 类(UIView 的子类),它根据框架在其初始化程序中设置其 radius像这样传入 init(frame: CGRect): override init
这是我的代码: import Foundation class Person: NSObject, NSCoding { var name: String init(name: String) {
如何使用 NSCoder 来编码和解码自定义类型? 例如,如何将 NSCoder 与“STATE”实例一起使用,其中: typedef enum { ON, OFF } STATE; 最佳答案 您可以
所以,我是 iOS 新手,一直在使用在线教程来学习该平台。我正在使用的教程是在我使用 iOS 10 的同时使用 iOS 9 构建应用程序。因此,我遇到了标题问题。这是一些代码: CalendarEve
在下面的代码中,sharedInstance 方法中的属性从未正确设置,我不明白为什么。在我用存档器保存它之前,我似乎有正确的值。 #import "User.h" static User *
所以,我是 iOS 新手,一直在使用在线教程来学习该平台。我正在使用的教程是在我使用 iOS 10 时使用 iOS 9 构建应用程序。因此我遇到了标题问题。这是一些代码: CalendarEvent.
我正在开发 iphone 应用程序。 我使用 NSCoder。 我的应用程序.h #define ITEMS_KEY @"items" #define CATEGORIES_KEY @"categor
我正在开发一个 iPhone 应用程序,但我的共享单例类遇到了一些问题。我使用共享单例来存储两个变量int gameRuns 和 int totalScore每次用户加载应用程序时,“gamRuns”
当使用NSCoder和NSKeyedArchiver时,我知道数据是以二进制格式存储的。那么,存储文件最合适的文件扩展名是什么?许多教程都使用 .plist,但我相信这应该是文本属性列表 ~ 键/值对
尝试在另一个类(Swipe)中实例化使用 NSCoder 的类(SettingsView)时遇到问题。 SettingsView 类已经是目标 -C 类(FXBlurView) 的实例 我收到以下错误
我正在开发我的第一个 Swift iOS 应用程序,在序列化和保存从服务器获取 JSON 的对象时遇到问题。我正在使用Gloss ,一个轻量级 JSON 解析库,它定义了一个 Decodable 协议
我定义了一个具有 [String] 和 Float 属性的类,它在 NSCoder 的编码过程中工作正常,但在解码时总是失败。我在代码中添加了guard let,发现是Float $的问题。 我不知道
我有一个用户Class使用 saveuser()每当应用程序终止时方法。用户有两个 Arrays定制Classes该子类NSObject 。这是我的编码方法。 func encode(with aCo
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 8 年前。 Improve th
当对象的属性在存档和取消存档过程之间发生变化时,我在使用 NSKeyedArchiver 和 NSKeyedUnarchiver 时遇到了一些麻烦。这是一个具体的例子: 我有一个类,比如说Task,它
这可能是一个幼稚的问题 - 但我想仔细检查以避免在 UIDocument 上浪费时间,如果它不符合我的要求的话。 背景:我有一个应用程序,我为其创建了一个简单的文件系统来将用户创建的文档保存为 pli
我有两个用于保存数据的模型类,我在解码数据时崩溃了。 第一类: class User: NSObject,NSCoding, Mappable { var authenticationToke
我基于此处的示例创建了 UILabel 的子类:UILabel doesn't show inputView .我正在尝试在子类化 UITableViewCell 的类中创建标签的实例。我遇到的问题是
我有一个对象,我必须使用 encodewithcoder 进行编码,但它是一个“长”数字,我不确定是否必须像简单的 int、int32 或 int64 那样对其进行编码。 Apple 的文档似乎对我来
我是一名优秀的程序员,十分优秀!