Programmatically Change data in a core data file - core-data

Hello All & Thanks in Advance!
I am a noob with Core Data and I need to change data in one of my fields which is named: recid.
I have created a index which again is: recid as int 16 in my core data model.
What I am needing to do is fetch the record and changed recid from we will say 5 to 1 how would I go about doing this?
Here is the code I have built so far & I will take care of my loop after I understand how to change the data in the record.
-(void)awakeFromNib
{
NSMenu *theMenu;
statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength] retain];
[statusItem setMenu:statusMenu];
[statusItem setImage:[NSImage imageNamed:#"TheJournal_16x16x32"]];
[statusItem setHighlightMode:YES];
theMenu = [[NSMenu alloc] initWithTitle:#""];
[theMenu addItemWithTitle:#"The Journal" action:#selector(showTheWindow:) keyEquivalent:#"W"];
[theMenu addItemWithTitle:#"Quit" action:#selector(terminate:) keyEquivalent:#"Q"];
[statusItem setMenu:theMenu];
[theMenu release];
NSUInteger count;
count = 0;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
count = [prefs integerForKey:#"recid"];
NSLog(#"counter is >>>>%lu",(unsigned long)count);
[prefs setInteger:count forKey:#"recid"];
count++;
NSUserDefaults *prefs1 = [NSUserDefaults standardUserDefaults];
[prefs1 setInteger:count forKey:#"recid"];
NSLog(#"counter is >>>>%lu",(unsigned long)count);
// How I fetch the record & change the value from 5 to 1?
}

Here's a code sample that may help you. In this example, the YourManagedClass Core Data entity uses a UUID string as a unique record identifier. The extension contains a static function that fetches the unique record, sets the new recid value and then saves the NSManagedObjectContext.
import Foundation
import CoreData
class YourManagedClass: NSManagedObject {
#NSManaged var uuid: String?
#NSManaged var recid: NSNumber?
}
extension YourManagedClass {
static func set(recID: Int16, forObject uuid: String, `in` context: NSManagedObjectContext) {
let fetchRequest = NSFetchRequest<YourManagedClass>(entityName: "YourManagedClass")
fetchRequest.predicate = NSPredicate(format: "uuid = %#", argumentArray: [uuid])
let object: YourManagedClass
do {
let objects = try context.fetch(fetchRequest)
guard let foundObject = objects.first else {
return
}
object = foundObject
} catch {
// Handle Error
return
}
object.recid = NSNumber(value: recID)
do {
try context.save()
} catch {
// Handle Error
}
}
}
You would then call this function with a reference to your NSManagedObjectContext ('context' here):
YourManagedClass.set(recID: 15, forObject: "909455F3-C812-4399-83B4-F96A5C32A71D", in: context)

Related

How to Fetch NSManagedObject from Core data given its type and property

I need to get a NSManagedObject from Core data so I can share it with cloud Kit. I fetch the result based on the entity property and type. Then I try to convert the result into NSManagedObject.
// Fetch NSManagedObject so it can be shared
if let estProfile: NSManagedObject = fetchEntity(uniqueId: self.energyProfileId!, entityType: EstEnergyProfile.self) {
print("fetched NSManagedObject for sharing with cloud kit")
}
//Fetch NSManagedObject given specific property and its type
func fetchEntity (uniqueId: String, entityType: NSManagedObject.Type) -> NSManagedObject?{
var obj: NSManagedObject? = nil
let context = appDelegate.persistentContainer.viewContext
do {
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = entityType.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "uniqueId == %#", uniqueId)
let fetchedResults = try context.fetch(fetchRequest)
obj = fetchedResults.first as NSManagedObject
}
catch {
print("Error fetching entity: ", entityType)
}
return obj
}
In the above code at the line
obj = fetchedResults.first as NSManagedObject
I get the error : 'NSFetchRequestResult?' is not convertible to 'NSManagedObject
I don't think I am doing this right. Can someone help fix this code?
I would make the fetch function generic
func fetchEntity<EntityType: NSManagedObject>(_: EntityType.Type, uniqueId: String) -> EntityType? {
let context = appDelegate.persistentContainer.viewContext
do {
let fetchRequest = EntityType.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "uniqueId == %#", uniqueId)
let fetchedResults = try context.fetch(fetchRequest)
return fetchedResults.first as? EntityType
}
catch {
print("Error fetching entity: ", error)
return nil
}
}
Example
let estProfile: NSManagedObject = fetchEntity(EstEnergyProfile.self, uniqueId: self.energyProfileId!)

NSManagedObject fetched into 2 different contexts has different attribute values

My app has a reproducible CoreData error.
I use the viewContext for display, and a backgroundContext for object updates. Both contexts belong to the same NSPersistentCloudKitContainer.
At some point, I save in the backgroundContext an object after updating its status attribute from 2 to 1, and its updatedAt attribute from nil to Date().
Later, I want to fetch back this updated object, and my understanding is that a fetch always returns the content of the persistent store.
Thus, the fetched object should be the same regardless into which context it is fetched. However, this is not the case.
I have also set -com.apple.CoreData.ConcurrencyDebug 1 as a launch argument, so this is not a CoreData multithreading error.
Here is my test code:
The object is saved here:
let context = backgroundContext!
context.performAndWait {
assert(ItemStatus(rawValue: item.status) == .isBought)
item.status = ItemStatus.isToBuy.rawValue
item.updatedAt = Date()
_ = saveContext(context)
}
with
func saveContext(_ context: NSManagedObjectContext) -> Error? {
if !context.hasChanges { return nil }
let inserts = context.insertedObjects; if !inserts.isEmpty { print("Will save inserted objects: \(inserts)") }
let updates = context.updatedObjects; if !updates.isEmpty { print("Will save updated objects: \(updates)") }
let deletes = context.deletedObjects; if !deletes.isEmpty { print("Will save deleted objects: \(deletes)") }
do {
try context.save()
print("\(context.name!) saved")
} catch {
fatalError("Unresolved error")
}
return nil
}
Later, I fetch the object into both contexts using:
let mwFetchRequest = NSFetchRequest<Item>(entityName: Item.entityName)
let passwordPredicate = NSPredicate(format: "\(Schema.Item.password) == %#", password)
let namePredicate = NSPredicate(format: "\(Schema.Item.name) == %#", "Mineral water")
let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [passwordPredicate, namePredicate])
mwFetchRequest.predicate = compoundPredicate
mwFetchRequest.returnsObjectsAsFaults = false
backgroundContext.performAndWait {
let bcItem = try! backgroundContext.fetch(mwFetchRequest)
print("backgroundContext: \(bcItem)")
}
viewContext.performAndWait {
let vcItem = try! viewContext.fetch(mwFetchRequest)
print(„viewContext: \(vcItem)")
}
And here is the log when I set a breakpoint after this code:
Will save updated objects: [<ShopEasy.Item: 0x600000d7cf50> (entity: Item; id: 0x9698d776a7665623 <x-coredata://35BF43D6-4CF7-490D-B944-9DDFF2823AA1/Item/p1617>; data: {
buyPlaces = "<relationship fault: 0x600002e296a0 'buyPlaces'>";
fixedAtTopAt = nil;
howOftenBought = 1;
lastBoughtDate = "2021-01-24 13:02:09 +0000";
name = "Mineral water";
password = "PW_1";
status = 1;
updatedAt = "2021-01-24 13:32:14 +0000";
})]
backgroundContext saved
…
backgroundContext: [<ShopEasy.Item: 0x600000d7cf50> (entity: Item; id: 0x9698d776a7665623 <x-coredata://35BF43D6-4CF7-490D-B944-9DDFF2823AA1/Item/p1617>; data: {
buyPlaces = "<relationship fault: 0x600002e296a0 'buyPlaces'>";
fixedAtTopAt = nil;
howOftenBought = 1;
lastBoughtDate = "2021-01-24 13:02:09 +0000";
name = "Mineral water";
password = "PW_1";
status = 1;
updatedAt = "2021-01-24 13:32:14 +0000";
})]
viewContext: [<ShopEasy.Item: 0x600000d75ae0> (entity: Item; id: 0x9698d776a7665623 <x-coredata://35BF43D6-4CF7-490D-B944-9DDFF2823AA1/Item/p1617>; data: {
buyPlaces = (
"0x9698d776b10e5621 <x-coredata://35BF43D6-4CF7-490D-B944-9DDFF2823AA1/Place/p971>"
);
fixedAtTopAt = nil;
howOftenBought = 1;
lastBoughtDate = "2021-01-24 13:02:09 +0000";
name = "Mineral water";
password = "PW_1";
status = 2;
updatedAt = nil;
})]
Obviously, the object is first correctly saved using the backgroundContext, and should thus be in the persistent store.
It is then fetched back correctly into the backgroundContext.
But after fetching the same object into the viewContext, the two changed attributes, status and updatedAt, have the values as they were before the save.
My questions:
Are my assumptions wrong? Is something wrong with my code?
Later, I want to fetch back this updated object, and my understanding
is that a fetch always returns the content of the persistent store.
The fetch selects the objects to return based on the content of the persistent store, but it does not by default update the in-memory copies of the objects based on the store’s content. There is an option to do this, which in my experience doesn’t work. To update an existing object from the store, you could refresh it or set up merging on your context so that changes to the store are automatically propagated.

Coredata returns duplicate values. Can anyone had the same issue?

Im using swift3. When fetching data from coredata, it returns duplicate values. Using software Datum, i understood that database only contains the original value.
class DatabaseManager: NSObject {
fileprivate static let sharedManager: DatabaseManager = DatabaseManager()
class var shared: DatabaseManager {
return sharedManager
}
/*Returns the ManagedObjectContext*/
var managedObjectContext: NSManagedObjectContext!
var privateManagedObjectContext: NSManagedObjectContext!
fileprivate var completionHandler: ((_ completed: Bool)-> Void)? = nil
override init() {
privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
if let appdelegate = UIApplication.shared.delegate as? AppDelegate {
managedObjectContext = appdelegate.managedObjectContext
privateManagedObjectContext.persistentStoreCoordinator = managedObjectContext.persistentStoreCoordinator
}
}
deinit {
managedObjectContext = nil
privateManagedObjectContext = nil
}
}
//Fetching data
func getItem()->[ListItem]{
var objects = [ListItem]()
var uniqueObjects:[ListItem] = [ListItem]()
let sort = NSSortDescriptor(key: "itemName", ascending: false)
let request : NSFetchRequest<ShoppyListItem> = ShoppyListItem.fetchRequest() as NSFetchRequest<ShoppyListItem>
//let predicate = NSPredicate(format:"excludedIDContain = %#","New")
// request.predicate = predicate
request.sortDescriptors = [sort]
do {
if objects.count > 0 {
objects.removeAll()
}
objects = try managedObjectContext?.fetch(request) ?? []
return objects
} catch {
print("Error with request: \(error)")
}
return objects
}
// objects = try managedObjectContext?.fetch(request) ?? [] returns duplicated objects
i got it. Im not mistaken about the count. It was due to concurrency. i was not running fetch on the safe thread of coredata. All i had to do was put the code inside perform block.
managedObjectContext.perform(block).
Got this from stanford ios tutorial named coredata demo. Video time 26:00. The professor explains this.

SWIFT - 'AnyObject' does not have a member name 'fooBar'

I am trying to fetch some data from Core Data and have run into a slight problem. I can fetch the data with no problem. The moment I try to grab a specific piece of data (i.e. data.fooBar), it throws up an error:
"'AnyObject' does not have a member name 'fooBar'
If I println(data) it will show that fooBar does exist with data stored in it.
I am not really sure why it is doing this. I have tried to search for an answer and tried a bunch of different things but none have seemed to work. Any help would be great. Thanks. :)
var results : Array<AnyObject> = []
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
//get the data for that storedItem
var appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var context:NSManagedObjectContext = appDel.managedObjectContext!
let req = NSFetchRequest(entityName: "storedItems")
let name:String = results[indexPath.row].name
req.predicate = NSPredicate(format: "name == %#", name)
req.returnsObjectsAsFaults = false
var tapResults = context.executeFetchRequest(req, error: nil)!
for item in tapResults {
println(item) //works, shows all data correctly(including subText)
println(item.name) //works, the only one that does for some reason???
println(item.subText) //Error 'AnyObject' does not have a member name 'subText'
}
Here is the result for: println(item)
println(item) <NSManagedObject: 0x7f04be60> (entity: storedItems; id: 0x7f041de0 <x-coredata://DD4F8E68-2234-46B5-B1D8-AE2F75245C63/storedItems/p1> ; data: {
alarmSound = default;
isDefault = 0;
name = "test";
sliderHours = 0;
sliderMinutes = 0;
sliderSeconds = 0;
subText = "00:00:00";
UPDATE: Based on discussion over vacawama answer (Thank you Aaron). For correct solution please see the answer I accepted.
my itemObj class
#objc(itemObj)
class itemObj: NSManagedObject {
#NSManaged var name:String!
#NSManaged var sliderHours:NSNumber
#NSManaged var sliderMinutes:NSNumber
#NSManaged var sliderSeconds:NSNumber
#NSManaged var subText:String!
#NSManaged var alarmSound:String!
#NSManaged var isDefault:NSNumber
}
my AddItem VC:
var tResults = (context.executeFetchRequest(req, error: nil))
for item in tResults as [itemObj!] {
println(item.name)
println(item.subText)
}
executeFetchRequest returns an optional array of AnyObject. You shouldn't force-unwrap it (this can cause a crash). So optionally unwrap it and do an optional cast (as?) to make sure the type is correct:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let req = NSFetchRequest(entityName: "storedItems")
let name:String = results[indexPath.row].name
req.predicate = NSPredicate(format: "name == %#", name)
req.returnsObjectsAsFaults = false
let tapResults = context.executeFetchRequest(req, error: nil)
if let presentResults = tapResults {
if let castedResults = presentResults as? [MyManagedObjectSubclass] {
for item in castedResults {
println(item)
println(item.name)
println(item.subText)
}
}
}
}
I also changed all of your vars to lets since they don't need to be mutable.
Just replace MyManagedObjectSubclass with whatever your NSManagedObject subclass is.

Store Integers in Core Data using Swift and XCode

While Strings appears to be fine I'm having some trouble storing Integers into Core Data. Following tutorials and reading available information out there doesn't seem to be helping me who has no Objective-C background. (Swift seemed like a straight forward language like the languages I'm fluent with PHP/OOPHP/JavaScript/VBScript/... thus I started playing with it and so far have been able to do everything I wanted, almost)
What I want to do now is, to receive the JSON data and store it into Core Data
Here's my Core Data
Entity name: Category
Its Attributes:
id Int16
title String
description String
My Swift model? file: Category.swift
import CoreData
class Category: NSManagedObject {
#NSManaged var id: Int //should I declare this as Int16?
#NSManaged var title: String
#NSManaged var description: String
}
I'm using SwiftyJASON extension? and NSURLSession protocol? to get the data and to parse it as follow:
import UIKit
import CoreData
class ViewController: UIViewController {
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
}
func fetchData() {
var url = NSURL.URLWithString("http://domain.com/index.php?r=appsync/read&id=category")
var session = NSURLSession.sharedSession()
session.dataTaskWithURL(url, completionHandler: {(data, response, error) in
// parse data into json
let json = JSONValue(data)
let entityDescription = NSEntityDescription.entityForName("Category", inManagedObjectContext: self.managedObjectContext)
let category = Category(entity: entityDescription, insertIntoManagedObjectContext: self.managedObjectContext)
for item in json.array! {
category.id = item["id"].string!.toInt()! //goes KABOOM!
category.title = item["title"].string!
category.description = item["description"].string!
managedObjectContext?.save(nil)
}
dispatch_async(dispatch_get_main_queue()) {
// do something
}
}).resume()
}
}
Let's assume the JASON data is:
[{"id":"1","title":"cat1","description":"blabala one"},{"id":"2","title":"cat2","description":"blabala two"}]
At line where it says category.id = item["id"].string!.toInt()! xCode goes KABOOM, what am I doing wrong here?
Notes/More questions:
I tried changing id type within Core Data to Int32 and then declaring it as just Int
in the model (and not Int16 or Int32) which reduced some errors but
xCode still crashes
Probably the way I'm looping stuff is not the best way to do this,
what's the better way of storing array of data into core data at
once?
Most of the tutorials I've seen there's no id's for Entities(tables), am I missing something here?
References:
SiftyJSON: https://github.com/lingoer/SwiftyJSON
Core Data tutorial:
http://rshankar.com/coredata-tutoiral-in-swift-using-nsfetchedresultcontroller/
EDIT > Working code:
Category.swift model file which can be auto generated using File>New>File>iOS>Core Data>NSManagedObject subclass [swift, no need for bridging header but you need to manually add #objc line as below]
import CoreData
#objc(Category) //Wouldn't work without this
class Category: NSManagedObject {
#NSManaged var id: NSNumber //has to be NSNumber
#NSManaged var title: String
#NSManaged var mydescription: String //"description" is reserved so is "class"
}
ViewController.swift
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
}
func fetchData() {
var url = NSURL.URLWithString("http://domain.com/index.php?r=appsync/read&id=category")
var session = NSURLSession.sharedSession()
session.dataTaskWithURL(url, completionHandler: {(data, response, error) in
let json = JSONValue(data)
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext //this line had to be moved here
let entityDescription = NSEntityDescription.entityForName("Category", inManagedObjectContext: managedObjectContext)
for item in json.array! {
let category = Category(entity: entityDescription, insertIntoManagedObjectContext: managedObjectContext) //this line has to be in inside for loop
category.id = item["id"].string!.toInt()!
category.title = item["title"].string!
category.mydescription = item["description"].string!
managedObjectContext?.save(nil)
}
dispatch_async(dispatch_get_main_queue()) {
// do something
}
}).resume()
}
}
Sample fetching data code:
func requestData() {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Category")
request.returnsObjectsAsFaults = false
var results:NSArray = context.executeFetchRequest(request, error: nil)
//println(results)
for category in results {
var cat = category as Category
println("\(cat.id),\(cat.title),\(cat.mydescription)")
}
}
P.S. Make sure to Clean your project and delete the app from simulator after changing Model
Scalar types (integers, floats, booleans) in core data are broken in the current Swift beta (5). Use NSNumber for the properties, and file a radar.
object.intProperty = NSNumber(int:Int(item["id"] as String))
(Typed on the phone, so sorry if that's wrong, and I know it's disgusting code - hence, file a radar!)
Or, in your specific case, looking at the JSON, use String. Those IDs are coming in as strings anyway.
Updated for Swift 2
If your JSON data is really of type [[String:String]], you can use the following code in order to set category.id:
if let unwrappedString = item["id"], unwrappedInt = Int(unwrappedString) {
category.id = unwrappedInt
}

Resources