【问题标题】:Unable to display images from Core Data properly无法正确显示来自 Core Data 的图像
【发布时间】:2015-12-26 03:06:23
【问题描述】:

我是 Core Data 的新手,遇到了一个问题。这个应用程序应该将照片库中的图像存储到核心数据中,并在集合视图中显示这些图像。

但是,问题是在模拟器上新安装应用程序并且您只需添加图片时显示的图片。但是当您关闭应用程序并再次打开时,它会崩溃并在控制台中显示错误:线程 1 EXC_BAD_ACCESS

// Loading Setup

@IBOutlet var collection: UICollectionView!
var images = [NSManagedObject]()

override func viewDidAppear(animated: Bool) {
    let managedContext = AppDelegate().managedObjectContext

    let fetchRequest = NSFetchRequest(entityName: "FullRes")

    do {
        let results =
        try managedContext.executeFetchRequest(fetchRequest)
        images = results as! [NSManagedObject]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
    collection.reloadData()

}
override func viewDidLoad() {
    super.viewDidLoad()
    imagePicker.delegate = self

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Register cell classes
    self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

// MARK: UICollectionViewDataSource

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}


override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return images.count
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MainCollectionViewCell
    let selectedObject = images[indexPath.row]
    print(selectedObject)
    let image: UIImage = UIImage(data: selectedObject.valueForKey("imageData") as! NSData!)!
    cell.imageView.image = image

    // Configure the cell

    return cell
}

// MARK: UICollectionViewDelegate

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
    return false
}

override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
    return false
}

override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {

}
*/

// Camera Setup

// the image picker
let imagePicker = UIImagePickerController()
// a queue to save the image without freezing the App UI
let saveQueue = dispatch_queue_create("saveQueue", DISPATCH_QUEUE_CONCURRENT)
// the Managed Object Context where we will save our image to.
let managedContext = AppDelegate().managedObjectContext

@IBAction func imageDidPress(sender: AnyObject) {
    imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
    presentViewController(imagePicker, animated: true, completion: nil)

}


@IBAction func addDidPress(sender: AnyObject) {
    imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    presentViewController(imagePicker, animated: true, completion: nil)

}

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    prepareImageForSaving(image)
    self.dismissViewControllerAnimated(true, completion: nil)

}

/*

func deletePhotoFromLibrary(info: [String : AnyObject]) {
        print("wasrun")
        let imageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
        let imageUrls = [imageUrl]
        //Delete asset
        PHPhotoLibrary.sharedPhotoLibrary().performChanges( {
            let imageAssetToDelete = PHAsset.fetchAssetsWithALAssetURLs(imageUrls, options: nil)
            PHAssetChangeRequest.deleteAssets(imageAssetToDelete)
            },
            completionHandler: { success, error in
                NSLog("Finished deleting asset. %@", (success ? "Success" : error!))
        })
    }

}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
}
*/


func prepareImageForSaving(image:UIImage) {
    // use date as unique id
    let date : Double = NSDate().timeIntervalSince1970


    // dispatch with gcd.
    dispatch_async(saveQueue) {

        // create NSData from UIImage
        guard let imageData = UIImageJPEGRepresentation(image, 1) else {
            // handle failed conversion
            print("jpg error")
            return
        }

        // scale image
        let thumbnail = self.scale(image: image, toSize: self.view.frame.size)

        guard let thumbnailData  = UIImageJPEGRepresentation(thumbnail, 0.7) else {
            // handle failed conversion
            print("jpg error")
            return
        }

        // send to save function
        self.saveImage(imageData, thumbnailData: thumbnailData, date: date)

    }
}

func saveImage(imageData:NSData, thumbnailData:NSData, date: Double) {

    dispatch_barrier_async(saveQueue) {
        // create new objects in moc
        guard let fullRes = NSEntityDescription.insertNewObjectForEntityForName("FullRes", inManagedObjectContext: self.managedContext) as? FullRes, let thumbnail = NSEntityDescription.insertNewObjectForEntityForName("Thumbnail", inManagedObjectContext: self.managedContext) as? Thumbnail else {
            // handle failed new object in moc
            print("moc error")
            return
        }

        //set image data of fullres
        fullRes.imageData = imageData

        //set image data of thumbnail
        thumbnail.imageData = thumbnailData
        thumbnail.id = date as NSNumber
        //set relationship between the two objects
        thumbnail.fullRes = fullRes

        // save the new objects
        do {
            try self.managedContext.save()
        } catch {
            // implement error handling here
            fatalError("Failure to save context: \(error)")
        }

        // clear the moc
        self.managedContext.refreshAllObjects()
    }


}

func scale(image image:UIImage, toSize newSize:CGSize) -> UIImage {

    // make sure the new size has the correct aspect ratio
    let aspectFill = resizeFill(image.size, toSize: newSize)

    UIGraphicsBeginImageContextWithOptions(aspectFill, false, 0.0);
    image.drawInRect(CGRectMake(0, 0, aspectFill.width, aspectFill.height))
    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

func resizeFill(fromSize: CGSize, toSize: CGSize) -> CGSize {

    let aspectOne = fromSize.height / fromSize.width
    let aspectTwo = toSize.height / toSize.width

    let scale : CGFloat

    if aspectOne < aspectTwo {
        scale = fromSize.height / toSize.height
    } else {
        scale = fromSize.width / toSize.width
    }

    let newHeight = fromSize.height / scale
    let newWidth = fromSize.width / scale
    return CGSize(width: newWidth, height: newHeight)

}

更新:根据下面的 cmets,我对代码进行了更改。

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MainCollectionViewCell
    if let imagePath = images[indexPath.row].imageData {
        cell.imageView.image = UIImage(data: imagePath)
    }
    // Configure the cell

    return cell
}

但现在,我收到另一个错误:2015-12-26 20:10:24.464 Collect[480:69113] -[Thumbnail imageData]: unrecognized selector sent to instance 0x13fe9ba00.

AppDelegate.swift 上的代码class AppDelegate: UIResponder, UIApplicationDelegate { 高亮显示。

有趣的是,应用程序一直工作到某个点。例如,当我从正在运行它的手机上卸载应用程序然后重新运行它时,它会运行一段时间,直到它崩溃。

但是,它并没有像我希望的那样完美地工作。有时,只有添加另一张图片才会出现一张图片。

更新 2:我根据您的以下 cmets 进行了一些调整:

override func viewDidAppear(animated: Bool) {
    authenticateUser()

    let managedContext = AppDelegate().managedObjectContext

    let fetchRequest = NSFetchRequest(entityName: "Thumbnail")

    managedContext.performBlockAndWait { () -> Void in
        do {
            let results =
            try managedContext.executeFetchRequest(fetchRequest)
            self.images = results as! [Thumbnail]
        } catch let error as NSError {
            print("Could not fetch \(error), \(error.userInfo)")
        }
    }

    collection.reloadData()

}

只要我删除应用程序并重新运行它,它就可以正常工作。但是,当应用关闭时,它不再具有恢复图像的能力。

我在运行它时仍然得到-[Thumbnail imageData]: unrecognized selector sent to instance 0x13762d650。 AppDelegate.swift 上突出显示的代码是class AppDelegate: UIResponder, UIApplicationDelegate {

【问题讨论】:

  • 你从哪部分得到错误信息?
  • 为什么在获取时不使用 NSManagedObject 子类?只需使用if let imageData = results as? [FullRes] 进行向下转换,同时查找可选绑定。当你应该使用 if let source of most of the code in the question 时,你使用了很多 !
  • @JasonNam let image: UIImage = UIImage(data: selectedObject.valueForKey("imageData") as!NSData!)!
  • @RMenke 你能解释一下吗?
  • 我怀疑导致 nil 值的潜在问题是线程/并发之一。看看NSManagedObjectContext 类引用的Concurrency section

标签: ios swift core-data uiimageview uicollectionview


【解决方案1】:

你是对的,我对另一个问题的回答有误。 CoreData 需要一个NSManagedObjectContext 中的所有操作发生在与创建它的线程相同的线程上。我更新了答案。

以下是相关代码:

UIViewController 中创建两个单独的队列

let convertQueue = dispatch_queue_create("convertQueue", DISPATCH_QUEUE_CONCURRENT) // this one is for image stuff
let saveQueue = dispatch_queue_create("saveQueue", DISPATCH_QUEUE_CONCURRENT) // this one is for CoreData

在正确的线程上设置 moc 的值

extension ViewController {

    // call this in viewDidLoad
    func coreDataSetup() {

        dispatch_sync(saveQueue) {
            self.managedContext = AppDelegate().managedObjectContext
        }
    }
}

保存图片:

extension ViewController {

    func saveImage(imageData:NSData, thumbnailData:NSData, date: Double) {

        dispatch_barrier_sync(saveQueue) {
            // create new objects in moc
            guard let moc = self.managedContext else {
                return
            }

            guard let fullRes = NSEntityDescription.insertNewObjectForEntityForName("FullRes", inManagedObjectContext: moc) as? FullRes, let thumbnail = NSEntityDescription.insertNewObjectForEntityForName("Thumbnail", inManagedObjectContext: moc) as? Thumbnail else {
                // handle failed new object in moc
                print("moc error")
                return
            }

            //set image data of fullres
            fullRes.imageData = imageData

            //set image data of thumbnail
            thumbnail.imageData = thumbnailData
            thumbnail.id = date as NSNumber
            thumbnail.fullRes = fullRes

            // save the new objects
            do {
                try moc.save()
            } catch {
                fatalError("Failure to save context: \(error)")
            }

            // clear the moc
            moc.refreshAllObjects()
        }
    }
}

【讨论】:

  • 谢谢。但是guard let moc = self.managedContext else { 会产生错误Initializer for conditional binding must have Optional type, not 'NSManagedObjectContext'。另外,我在哪里打电话CoreDataSetup(),什么时候使用convertQueue
  • @user139863 检查我评论中的链接问题。已更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 2021-09-26
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多