将 NSCollectionView 与 CoreData 和 NSImageView 一起使用

Using NSCollectionView with CoreData and an NSImageView

我正在尝试设置一个绑定到实体的 NSCollectionView,并且我正在尝试从该实体中将图像加载到 NSImageView 中。我将图像存储为 NSData 对象。
我做了一些研究,发现我应该设置一个 ValueTransformer 但我无法完成这项工作。

这是我的图像属性 pdfImage 保存过程的代码:

pdf = NSData(contentsOfFile: path)

            // pdf to image
            let pdfImageRep = NSPDFImageRep(data: pdf)
            let factor: CGFloat = 300/72

            pdfImageRep?.currentPage = 1
            let image = NSImage(size: self.frame.size, flipped: false,
                drawingHandler: {
                    dstRect in

                    (pdfImageRep?.drawInRect(dstRect))!
                    return true
            })

            let scaledImageRep = image.representations.first
            scaledImageRep?.pixelsWide = Int((pdfImageRep?.size.width)! * factor)
            scaledImageRep?.pixelsHigh = Int((pdfImageRep?.size.height)! * factor)

            let pngImageRep = NSBitmapImageRep(data: image.TIFFRepresentation!)
            let imageData = pngImageRep?.representationUsingType(NSBitmapImageFileType.NSJPEGFileType, properties: [:])

            pdfImage = imageData

我稍后在代码中保存 pdfImage。

正如我所说,我尝试使用 NSKeyedUnarchiveFromData 作为 ValueTransformer,但它没有用。

是我做错了还是有更简单的方法?有人可以帮我解决这个问题吗?

非常感谢!

我将 NSImage 存储在核心数据中。数据模型中的类型是可转换的。

anImage = [[NSImage alloc] initWithContentsOfURL:aFileURL];
if (anImage) {
    anImageObject = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:[self managedObjectContext]];
    [anImageObject setImage:anImage];
}

我在没有值转换器的情况下将 NSImageView 的值绑定到图像 属性。

ps。如果您在 Core Data 中存储图像数据(或其他 blob),请将图像放在单独的实体或存储路径中。见 blob section of the Core Data Programming Guide.