2016-02-26 80 views
3

我有这样的代码:斯威夫特 - NSCoder和PHAsset

import Foundation 
import Photos 

class PostItem: NSObject, NSCoding { 
    var postDate: String? 
    var postTitle: String? 
    var postText: String? 
    var postImages: [PHAsset]? 

    func encodeWithCoder(aCoder: NSCoder) { 
     aCoder.encodeObject(postDate, forKey: "postDate") 
     aCoder.encodeObject(postTitle, forKey: "postTitle") 
     aCoder.encodeObject(postText, forKey: "postText") 
     aCoder.encodeObject(postImages, forKey: "postImages") 
    } 

    required init?(coder aDecoder: NSCoder) { 
     postDate = aDecoder.decodeObjectForKey("postDate") as? String 
     postTitle = aDecoder.decodeObjectForKey("postTitle") as? String 
     postText = aDecoder.decodeObjectForKey("postText") as? String 
     postImages = aDecoder.decodeObjectForKey("postImages") as? [PHAsset] 
     super.init() 
    } 

    override init() { 
     super.init() 
    } 
} 

当我实现了一个功能:

func savePosts() { 
    let data = NSMutableData() 
    let archiver = NSKeyedArchiver(forWritingWithMutableData: data) 

    print("\(archiver)") 

    archiver.encodeObject(posts, forKey: "Posts") 
    archiver.finishEncoding() 
    data.writeToFile(dataFilePath(), atomically: true) 
} 

我有一个错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PHAsset encodeWithCoder:]: unrecognized selector sent to instance 0x7fb6dc01a050' 

一切工作正常,直到我将PHAsset添加到encodeWithCoder函数中。 PHAsset遵循NSCoder协议?

+0

号只为'NSObject'和'NSCopying'根据文件与本地标识符检索资产。 – Larme

+0

但PHAsset是NSObject –

+1

'NSObject'不符合'NSCoding'。您必须将PHAsset封装到允许NSCoding的自定义类中。 – Larme

回答

0

无需将PHAsset封装到符合NSCoding的对象中。

每个PHAsset有.localIdentifier,您可以将它保存为字符串和恢复资产时,使用 fetchAssetCollectionsWithLocalIdentifiers:options: