首页 > 解决方案 > 核心数据图像不持久?

问题描述

我在视图控制器中使用此功能存储和创建帖子:

@objc func createPost(){
        guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
        }
        let managedContext =
            appDelegate.persistentContainer.viewContext
        let post = Post(context: managedContext)

        var mediaURI: URL?
        let timeInSeconds = Int64((postDate?.timeIntervalSince1970)!)
        if isVideo == true {
            let filename = String(timeInSeconds) + ".MOV"
            FileService.uploadVideo(videoURL: pickedVideoURL, name: filename)
            post.mediaFilename = filename
        } else {
            let filename = String(timeInSeconds) + ".JPG"
            FileService.uploadImage(image: postImage, name: filename)
            post.mediaFilename = filename
        }
        var postTags:[Tag] = []

        if let tokens = tagsView.tokens() {
            for token in tokens {
                let tagFetchRequest: NSFetchRequest<Tag> = Tag.fetchRequest()
                tagFetchRequest.predicate = NSPredicate(format: "name == %@", token.title)
                do {
                    let res = try managedContext.fetch(tagFetchRequest)
                    var tag: Tag!
                    if res.count > 0 {
                        tag = res.first
                    } else {
                        tag = Tag(context: managedContext)
                        tag.name = token.title
                        tag.mostRecentUpdate = NSDate()
                        tag.mostRecentThumbnail = postImage?.jpegData(compressionQuality: 1.0) as NSData?
                    }
                    postTags.append(tag)
                } catch let error as NSError {
                    print("Could not fetch. \(error), \(error.userInfo)")
                    return
                }
            }
        }
        for tag in postTags {
            post.addToTags(tag)
        }
        post.isVideo = isVideo!
        post.thumbnail = pickedPostThumbnail?.jpegData(compressionQuality: 1.0) as NSData?
        post.notes = notesView.text
        post.timeStamp = postDate! as NSDate
        do {
            try managedContext.save()
            dismiss(animated: true, completion: nil)
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
    }

我在那里做了很多事情,但值得注意的是,我将带有 UIImage 的 post.thumbnail 设置为 NSData?最后我正在保存上下文。

所以我创建帖子并关闭应用程序,然后再次打开它,另一个视图控制器执行此操作:

 fileprivate lazy var posts: NSFetchedResultsController<Post> = {
    let appDelegate =
        UIApplication.shared.delegate as? AppDelegate
    let managedContext =
        appDelegate?.persistentContainer.viewContext
    let request: NSFetchRequest<Post> = NSFetchRequest(entityName: "Post")
    request.predicate = NSPredicate(format: "%@ IN self.tags", tag)
    let timeSort = NSSortDescriptor(key: "timeStamp", ascending: true)
    request.sortDescriptors = [timeSort]

    let posts = NSFetchedResultsController(fetchRequest: request, managedObjectContext: managedContext!, sectionNameKeyPath: nil, cacheName: nil)
    posts.delegate = self
    return posts
}()

override func viewDidLoad(){ 
....
do {
        try posts.performFetch()

} catch let error as NSError {
       print("Could not fetch. \(error), \(error.userInfo)")
}
...
}

let post = posts.object(at: indexPath)
cell.mediaFileName = post.mediaFilename
if let data = post.thumbnail {
        print(data,"data?")
        cell.thumbnail.image = UIImage.init(data: data as Data)
    } else {
        print("couldn't find")
    }

这在前几次重新启动时工作正常。然而很快,它开始打印(“找不到”)并且不加载图像。与帖子相关的其他字段仍在加载中。这是在 Xcode 附带的 iPhone 8 模拟器上运行的。

我在这里做错了什么?模拟器如何将图像存储在不持久的核心数据中?还是我滥用了托管上下文?

标签: iosswiftcore-data

解决方案


推荐阅读