ios – NSFetchRequest Assortment.first At all times Returning Entity from Empty Retailer

[ad_1]

I’ve the next code that at all times returns an occasion of Member, when it must be returning nil. It doesn’t matter what I enter for username, and irrespective of what number of occasions I delete the app from the simulator, the throw is at all times triggered from the create perform.

class MemberViewModel: ObservableObject {
    ...

    func create() throws -> Void {
        let context = Self.container.viewContext

        if entity!.username != nil {
            if strive Self.fetch(username: entity!.username!) != nil {
                throw MemberError.UserExists(username: entity!.username!)
            }

            if context.hasChanges {
                strive context.save()
            }
        }
    }

    static personal func fetch(username: String) throws -> Member? {
        let fetchRequest: NSFetchRequest<Member> = Member.fetchRequest()
        let context = Self.container.viewContext

        fetchRequest.predicate = NSPredicate(format: "username[c] == %@", username)
        return strive? context.fetch(fetchRequest).first
    }

    ...
}

extension MemberViewModel {
    public enum MemberError: Error {
        case UserExists(username: String)
    }
}

The calling code seems like:

extension MemberView {
    func save() -> Void {
        if (identify.isEmpty) {
            nameError = "A reputation have to be offered to proceed"
        }

        if (username.isEmpty) {
            usernameError = "A username or e-mail have to be offered"
        }

        if (nameError != nil || usernameError != nil) {
            return
        }

        do {
            let mvm = MemberViewModel(identify: identify, username: username, password: password, age: age, position: position, admin: admin, imageName: AVATARS[selectedImage], imageTint: selectedTint)
            strive mvm.create()

            web page = nil
        } catch MemberViewModel.MemberError.UserExists(let username) {
            usernameError = "The username (username) is already taken"
        } catch {
        }
    }
}

[ad_2]

Leave a Reply