ios - 无法正确显示核心数据中的图像

标签 ios swift core-data uiimageview uicollectionview

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

但是,问题是当应用程序新安装在模拟器上时,您只需添加图片即可显示图片。但是,当您关闭应用程序并再次打开时,它会崩溃并在控制台中显示错误:Thread 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)

}

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

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]: 无法识别的选择器发送到实例 0x13fe9ba00。

AppDelegate.swift 上的代码 class AppDelegate: UIResponder, UIApplicationDelegate { 已突出显示。

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

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

更新2:我根据您的以下评论做了一些调整:

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 {

最佳答案

你是对的,我在另一个问题上的回答有错误。 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()
        }
    }
}

关于ios - 无法正确显示核心数据中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34468159/

相关文章:

具有泛型参数的 Swift 3 泛型扩展约束

ios - 替换 iOS .ipa 文件的数据容器

iphone - 用于操作 UITableViewController 中核心数据的开源 UI 框架

objective-c - 从两个指针数组中检索关系

iphone - 如何在 Photos.app 中创建 iPhone "photofolder"

ios - 添加新的 Root View Controller

使用 Sinch 和 Swift 进行 iOS 推送通知

iOS 8 swift : editing NSManagedObject with segue: error when declaring types

ios - 几秒钟后显示警报 View

ios - glDrawElements 三角形使用顶点数组开始和结束的顶点渲染(使用 GL_TRIANGLE_STRIP)