3
votes

I'm trying to add CoreData to my application. This application is going to be a photo application, and give the user the ability to store photos in albums. I have two Entities in CoreData currently, Photo and Album.

The Album entity has four attributes. albumCoverImageData: Binary Data, id: UUID, name: String, passwordProtected: Boolean. In addition to these attributes, it has a relationship photos destination Photo Inverse Album.

The Photo Entity has two attributes, id: UUID and imageData: BinaryData

When trying to add a new album to the database, upon trying to save the context, the application crashes with the following error.

2020-10-20 15:49:33.889808-0400 LockIt[902:92475] -[__NSConcreteUUID compare:]: unrecognized selector sent to instance 0x2817b4fe0

2020-10-20 15:53:28.604954-0400 LockIt[902:92475] [error] error: Serious application error.  Exception was caught during Core Data change processing.  This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification.  -[__NSConcreteUUID compare:]: unrecognized selector sent to instance 0x2817b4fe0 with userInfo (null)

CoreData: error: Serious application error.  Exception was caught during Core Data change processing.  This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification.  -[__NSConcreteUUID compare:]: unrecognized selector sent to instance 0x2817b4fe0 with userInfo (null)

2020-10-20 15:53:28.622315-0400 LockIt[902:92475] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSConcreteUUID compare:]: unrecognized selector sent to instance 0x2817b4fe0'

*** First throw call stack:

(0x1937c65ac 0x1a78b442c 0x1936d0a2c 0x1937c9130 0x1937cb420 0x194b18c90 0x1998e5dc8 0x1998e58a0 0x1998e6ad0 0x1998e77b4 0x19989a410 0x199767b64 0x1998e7100 0x193725764 0x193725718 0x193724cd4 0x1937246a0 0x1949bc5f4 0x199892118 0x1998a0c50 0x199892fc0 0x199761aa0 0x104503bd8 0x104502e68 0x104502854 0x199fd2c04 0x19a2c3ec0 0x19a049990 0x19a0499b8 0x19a049990 0x19a03a1dc 0x19a088444 0x19a4d8f58 0x19a4d71a4 0x19a4d7d78 0x195c4d334 0x196177a4c 0x195c43350 0x195c43030 0x19612ef80 0x196108bc0 0x196190118 0x196193070 0x19618a5f4 0x19374381c 0x193743718 0x193742a28 0x19373cd20 0x19373c4bc 0x1aa24e820 0x1960e9164 0x1960ee840 0x1044f2178 0x193403e40)

libc++abi.dylib: terminating with uncaught exception of type NSException

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSConcreteUUID compare:]: unrecognized selector sent to instance 0x2817b4fe0'

terminating with uncaught exception of type NSException

I have attached relevant Files below. Photo Entity in Data Model Photo+CoreDataProperties

import Foundation

import CoreData





extension Photo {



    @nonobjc public class func fetchRequest() -> NSFetchRequest<Photo> {

        return NSFetchRequest<Photo>(entityName: "Photo")

    }



    @NSManaged public var id: UUID?

    @NSManaged public var imageData: Data?

    @NSManaged public var album: Album?



}



extension Photo : Identifiable {



    public var wrappedID: UUID {

        id!

    }

    

    public var wrappedImageData: Data {

        imageData!

    }

}

Album Entity in Data Model Album+CoreDataProperties

import Foundation

import CoreData





extension Album {



    @nonobjc public class func fetchRequest() -> NSFetchRequest<Album> {

        return NSFetchRequest<Album>(entityName: "Album")

    }



    @NSManaged public var albumCoverImageData: Data?

    @NSManaged public var id: UUID?

    @NSManaged public var name: String?

    @NSManaged public var passwordProtected: Bool

    @NSManaged public var photos: NSSet?

    

    public var wrappedID: UUID {

        id!

    }

    

    public var wrappedAlbumCoverImageData: Data {

        albumCoverImageData!

    }

    

    public var wrappedName: String {

        name ?? "Unamed Album"

    }

    

    public var wrappedPasswordProtected: Bool {

        passwordProtected

    }

    

    public var photoArray: [Photo] {

        let set = photos as? Set<Photo> ?? []

        

        return Array(set)

    }



}



// MARK: Generated accessors for photos

extension Album {



    @objc(addPhotosObject:)

    @NSManaged public func addToPhotos(_ value: Photo)



    @objc(removePhotosObject:)

    @NSManaged public func removeFromPhotos(_ value: Photo)



    @objc(addPhotos:)

    @NSManaged public func addToPhotos(_ values: NSSet)



    @objc(removePhotos:)

    @NSManaged public func removeFromPhotos(_ values: NSSet)



}



extension Album : Identifiable {

    

}

Main View

import SwiftUI



struct AlbumCollectionView: View {

    @Environment(\.managedObjectContext) var managedObjectContext

    @FetchRequest(entity: Photo.entity(),

                  sortDescriptors: [

                    NSSortDescriptor(keyPath: \Photo.id, ascending: true)

                  ]

    ) var photos: FetchedResults<Photo>

    

    @FetchRequest(entity: Album.entity(),

                  sortDescriptors: [

                    NSSortDescriptor(keyPath: \Album.name, ascending: true)

                  ]

    ) var albums: FetchedResults<Album>

    

    @State private var showingImagePicker = false

    @State private var showingPopover = false

    @State private var inputImage: UIImage?

    @State private var albumNameInput: String = ""

    

    let columns = [

        GridItem(.adaptive(minimum: 150))

    ]

    

    var body: some View {

        ScrollView {

            LazyVGrid(columns: columns, spacing: 20) {

                ForEach(albums) { album in

                    NavigationLink(destination: AlbumView(album: album)) {

                        VStack {

                            Image(data: album.albumCoverImageData, placeholder: "No Image")

                                .resizable()

                                .aspectRatio(1, contentMode: .fill)

                                .contextMenu(menuItems: {

                                    Button(action: {

                                        deleteAlbum(selectedAlbum: album)

                                    }) {

                                        Label("Remove", systemImage: "trash")

                                    }

                                })

                            Text(album.name ?? "")

                        }

                    }

                }

            }

            .padding()

            .navigationBarTitle(Text("Albums"))

            .navigationBarItems(trailing:

                Menu {

                    Button(action: {

                        self.showingPopover = true

                    }) {

                        Label("Add Album", systemImage: "photo.on.rectangle.angled")

                    }

                    Button(action: {

                        self.showingImagePicker = true

                    }) {

                        Label("Add Photo", systemImage: "photo")

                    }

                } label: {

                    Image(systemName: "plus")

                        .popover(isPresented: $showingPopover, arrowEdge: .trailing ,content: {

                            VStack {

                                Text("New Album")

                                TextField("Enter Album Name",text: $albumNameInput)

                                    .textFieldStyle(RoundedBorderTextFieldStyle())

                                Button("Submit"){

                                    addAlbum(name: albumNameInput, albumCover: UIImage(named: "Image 1")!)

                                    albumNameInput = ""

                                    showingPopover = false

                                }

                            }

                            .padding()

                        })

                }

            )

            .sheet(isPresented: $showingImagePicker, onDismiss: loadImage) {

                ImagePicker(image: self.$inputImage)

            }

        }

    }

    

    func addAlbum(name: String, albumCover: UIImage) {

        let newAlbum = Album(context: managedObjectContext)

        

        newAlbum.id = UUID()

        newAlbum.name = name

        newAlbum.passwordProtected = false

        newAlbum.albumCoverImageData = albumCover.jpegData(compressionQuality: 1.0)

        

        saveContext()

    }

    

    func deleteAlbum(selectedAlbum: Album) {

        for album in albums {

            if selectedAlbum == album {

                self.managedObjectContext.delete(album)

            }

        }

        saveContext()

    }

    

    func loadImage() {

        guard let inputImage = inputImage else { return }

        addPhoto(image: inputImage)

    }

    

    func addPhoto(image: UIImage) {

        let newPhoto = Photo(context: managedObjectContext)

        

        newPhoto.id = UUID()

        newPhoto.imageData = image.jpegData(compressionQuality: 1.0)

        

        saveContext()

    }

    

    func saveContext() {

        do {

            try managedObjectContext.save()

        } catch {

            print("Error saving managed object context: \(error)")

        }

    }

}

I'm at a loss as to what could be going on here, appreciate any insight!

1
Have you changed your core data model recently without generating new files (or manually updating the existing ones)?Joakim Danielson
I don't believe so, I can update the post with a screenshot of it to make sure there's no differences, but to my knowledge I haven't and there shouldn't be any differences.JoshHolme
We don't need a screenshot, that is something you can check yourself. I saw some similar issue and that was caused by an update data model so that's why I asked.Joakim Danielson
I haven't changed it, but I also haven't generated new files yet. After I generated the files I added the wrapped properties, but those are the only changes that I have made.JoshHolme
Off-topic but it might be better to add your own computed properties and other stuff in an extension to the entity class in a separate fileJoakim Danielson

1 Answers

7
votes

You say the problem occurs when adding and saving a new Album, though I think the issue actually relates to Photos. The error:

reason: '-[__NSConcreteUUID compare:]: unrecognized selector sent to instance

is in old Objective-C terminology (CoreData is at its heart Objective-C based). It indicates that there is an object of type __NSConcreteUUID (which is presumably the type of object that CoreData uses to store your UUIDs) and CoreData is trying to call the compare method on that object. compare is the method that gets called when sorting objects: compare object A with object B to work out what order they should be placed relative to each other.

So, the source of the problem is that your views are sorting something by UUID, and that appears to be the Photos:

     @FetchRequest(entity: Photo.entity(),
         sortDescriptors: [
             NSSortDescriptor(keyPath: \Photo.id, ascending: true)
             ]
         ) var photos: FetchedResults<Photo>

but UUIDs cannot be sorted in that way. Unless there is good reason for sorting by UUID, I would just change the sort order to use a different attribute.