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?
I personally have always use standard Swift
Inttypes for managed Core Data properties. In my experience theNSManagedObjectsubclasses have automatically provided me with this, but if it's generatingNSNumberfor you there may be a simple way to change it (I haven't done Core Data in Xcode 8 yet).Anyway,
NSNumberis just a wrapper around a number, so you can get the actual value out viaintValue.After you've changed everything (provided that the changes have happened on
NSManagedObjectsubclasses and properties marked@NSManged), you can save by callingsave()on the context.