Core Data - Editing, Incrementing and Saving Attribute to already exisiting Entity

65 views Asked by At

Ok, so i'm new to CoreData and using NSNumber (about a Day) and I watched a tutorial on CoreData and managed to store a number of different Achievements in coreData using the same entity which I called "Achievement" but now I am trying to fetch the data based on a name given to search for a specific "achievement" and edit its attribute.

func addOneToAchievement(AchName: String) {

    let getDataRequest:NSFetchRequest<Achievement> = Achievement.fetchRequest()
    getDataRequest.predicate = NSPredicate(format: "theSearchName == %@" , AchName)

    do {

        let searchResults = try CoreDatabaseContoller.getContext().fetch(getDataRequest)

        //print("number of results: \(searchResults.count)")

        for result in searchResults as [Achievement] {

           // print("\(result.theName!) \(result.theDescription!) is \(result.theImage!) \(result.aAmount!) / \(result.aNeededAmount!) is \(result.aStage!)")

            result.aAmount! += 1

            if result.aAmount! == result.aNeededAmount {

                 result.theImage! = "diamonds2"
                 result.aNeededAmount! = 100
                 result.aStage! = 2

            }
        }
    }

    catch {

        print("ERROR: \(error)")

    }
}

But I run into a problem, for the amount attribute of my entity is an NSNumber and have found that I can't increment it by the usual syntax of

result.Amount! += 1 

How can I increment the NSNumber of result.Amount! and then save it along with all the other attributes that I have changed of that certain achievement?

1

There are 1 answers

0
Matthew Seaman On BEST ANSWER

I personally have always use standard Swift Int types for managed Core Data properties. In my experience the NSManagedObject subclasses have automatically provided me with this, but if it's generating NSNumber for you there may be a simple way to change it (I haven't done Core Data in Xcode 8 yet).

Anyway, NSNumber is just a wrapper around a number, so you can get the actual value out via intValue.

let amount = result.aAmount!.intValue
a = NSNumber(value: amount + 1)

After you've changed everything (provided that the changes have happened on NSManagedObject subclasses and properties marked @NSManged), you can save by calling save() on the context.

do {
    try CoreDatabaseContoller.getContext().save()
} catch {
    // Error on Save
}