Core data Concerns about Core Data

I'm getting ready to dive into my first Core Data adventure. While evaluating the framework two questions came up that really got me thinking about using Core Data at all for this project or to stick with SQLite. My app will heavily rely upon importing data from an external source. I'm aware that one can import into Core Data but handling complex relationships seems complicated and tedious. Is there an easy way to accomplish complex imports? The app has to be able to execute complex queries sp

Core data CoreData: fetch only last elements, not all (iPhone)

Welcome i use Core Data to store datas. i need such a method which returns only the last 7 elements of entity. my question is how should i modify this code ( it fetchs all of elements, but i need only last 7) NSEntityDescription *entity = [NSEntityDescription entityForName:@"Trip" inManagedObjectContext:managedObjectContext]; NSFetchRequest *request = [[ NSFetchRequest alloc] init]; [request setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"dista

Core data FetchRequests from three entities with to-many relations, Core Data

this website has been an extremely helpful resource for me during the last weeks, since I just started coding in XCode. Now I came across a Core Data problem that I'd know how to solve in a common database, but not in Core Data and I'd be glad if someone could point me to the solution. I'd be fine with some keywords to do further research on, so here's the issue: Let's take a recipe example, linking ingredients to recipes: say you have an entity of ingredients, each of which can occur in severa

Core data Difference between UIManagedDocument saveToURL and UIManagedDocumentContext save

I'm debugging a Core Data issue in my app (running on iOS 5), where the changes to existing managed objects are not being persisted between app sessions. If I use [UIManagedDocumentContext save], nothing happens, and my changes are lost next time I restart the app. If I use [UIManagedDocument saveToURL], however, the changes do get saved. The Apple docs are unclear as to which is the right way of persisting the updates. Can someone explain the difference between the two, and when to use each met

Core data Approach for "calculated fields" on NSManagedObject subclass

I'd like to place some custom methods directly into each NSManagedObject. Think, "calculated fields": these methods provide read-only calculated values based upon persistent values on the Entity - which is identical to this question. I'm using the Xcode New File... Wizard to create NSManagedObject subclasses for each of my Entities. I'm trying to benefit from the system auto-creating the accessors for me. For example: Core Data Entity: "Site" @interface Site : NSManagedObject As I contin

Core data What is conflict in NSManagedObject and what's the different between some of the merge Policy?

NSMergeByPropertyObjectTrumpMergePolicy and NSOverwriteMergePolicy is the same in one thing. The property overwrite the one in the store. So what's the different between them? In all cases I can think of, whether the one in persistent store have changed or not, the property override the persistent store. Also what is conflict? I thought conflict simply means that the data are different. Does this mean that core data is originally designed that once data is written it cannot be updated? If co

Core data Core data parent child relationship

I have a basic question regarding Core Data. I have 2 tables one to many. I have setup the app to add children to the parent, but I cannot understand how I set the relationship so that when I add a new child via a view controller that It adds the child to the correct parent. I have generated the entity subclasses and have managed to get the app to add a child (but it adds it to index 0), but I cant seem to work a fetchrequest that finds the correct parent. - (IBAction)save:(id)sender { NSMa

Core data What is needed to make sure new versioning-enabled Core Data files go with the app?

I set up my working Core Data sqlite file for versioning. The versioning setup process created 3 files: foo.sqlite foo.sqlite-shm foo.sqlite-wal Since then, I can access the Core Data store programmatically (using MagicalRecord), but I can't read any data using either the Firefox add-in (SQLite Manager) or the app SQLiteManager. I'm concerned that when I send the updated app to the App Store, the additional files are not going to go and the app is going to crash. What do I need to do to m

Core data Reduce the retry time in CoreData - see below

This is what appears in the log, see the Retrying after delay: 60 seconds 2013-10-09 15:21:59.807 MyApp[4848:6507] -[PFUbiquitySafeSaveFile waitForFileToUpload:](299): CoreData: Ubiquity: <PFUbiquityPeerReceipt: 0x15e09de0>(0) permanentLocation: <PFUbiquityLocation: 0x15e22100>: /var/mobile/Library/Mobile Documents/HHWT75NS6T~com~xyz~MyApp/CoreData/New Project retry 2/mobile~A3BF465A-15C7-46F2-8C68-AC8F49FD15AB/New Project retry 2/W8MckEJ0x2d~HZZIeUH2be6hs41TEOONzKIrCuLcuP

Core data NSFetchedResultsController with predicate ignores changes merged from different NSManagedObjectContext

I am presenting table view contents using NSFetchedResultsController which has a predicate: [NSPredicate predicateWithFormat:@"visible == %@", [NSNumber numberWithBool:YES]] On background thread using separate NSManagedObjectContext I update few of the entities and change theirs visible value from NO to YES. Save, merge changes in main thread's NSManagedObjectContext. But NSFetchedResultsController's fetchedObjects doesn't change. Also controller doesn't call -controller:didChangeObject:... o

Core data Can I make a NSPredicate with a condition that an attribute is not found?

I have an abstract entity with 5 sub-entities. I want to fetch 4 sub-entities. The one entity I want to exclude have an attribute "note" that other entities not include. So can I make a predicate with the condition that the attribute "note" is not found to fetch the 4 sub-entities? I want only make a fetch request, because I use NSFetchedResultsController as data source of a table view.

Core data How can Order Many-to-Many with Ordered relationships

Ordered relationships works great... but i have not found documentation about how can use the check "ordered" in the fetch controller. My problem is: How i can sort the fetchcontroller? What's the key (SORT_VALUE) to use in -sortDescriptorWithKey:ascending: eg: NSSortDescriptor *sortPlaylistSongs = [NSSortDescriptor sortDescriptorWithKey:@"SORT_VALUE" ascending:YES]; Thank you.

Core data Setting up relationship in the code, after both parent and child are inserted with Core Data?

I have an app that uses core data with two entities: System and Owner. Each System has one Owner and each Owner can 'own' many System objects. Both objects are gathered from a remote JSON feed independently of each other. I GET all the Owner objects and load them to disk with Core Data, then I GET all the System objects and load those to disk using Core Data. Something like this: Owner.createInManagedObjectContext(self.managedObjectContext!, ownerID: reducedID, fName: fName, lName: lName)

Core data Pass NSManagedObjectContext between threads

Is it safe to initialize NSManagedContext in one thread and then pass it to another thread where you do inserts/fetches inside performBlock: ? So https://stackoverflow.com/a/12876800/2645683 mentions performBlock: and relates to my question but its not sufficient. It doesnt explicity say anything about thread which created context, and thread that executes block, and fact that these will be different threads. Answer https://stackoverflow.com/a/12874637/2645683 seems to be outdated. Since you

Core data How to access NSFetchRequest results in Swift 3?

Let's say that I want to fetch some NSManagedObjects from Core Data and enumerate all the results: let request = NSFetchRequest<NSFetchRequestResult>() let entityDesc = NSEntityDescription.entity(forEntityName: "Chapter", in: context) request.entity = entityDesc do { let result = try context.execute(request) } catch { print("\(error)") } Now I have a NSPersistentStoreResult object as result of the query, but I don't know what to do with it. The class documentation is empty:

Core data What NSNumber (Integer 16, 32, 64) in Core Data should I use to keep NSUInteger

I want to keep NSUInteger into my core data and I don't know which type should I use (integer 16, 32, 64) to suit the space needed. From my understanding: Integer 16 can have minimum value of -32,768 to 32,767 Integer 32 can have minimum value of -2,147,483,648 to 2,147,483,647 Integer 64 can have minimum value of -very large to very large and NSUInteger is type def of unsigned long which equal to unsigned int (Types in objective-c on iPhone) so If I convert my NSUInteger to NSNumber with n

Core data How to compute with Core Data

I'm trying to make a small program that keeps count of the amount of times pressed on a button. I'm using Core Data to store the information. The only problem is that I can't figure out how to compute with the information in the core data. If someone can tell me how to make a variable in the code equal to the value of the information in the Core Data I know enough. If there is another way to compute with the Core Data I would like to know about. import UIKit import CoreData class ViewControlle

Core data Swift4 CoreData -- NSManagedObjectModel catch a fatal error

I am now studying coreData in Swift. I made a simple test model to test CoreData, but failed. (xcode 9.3, Entites were created with Codegen "Class Definition"). Established coreDataStack in a independent swift file and built project, it caught a fatal error. "Fatal error: Unexpectedly found nil while unwrapping an Optional value", and I do not know how to deal with this. Please feel free to contact me if you need other detail. Your help would be highly appreciate. class coreDataStack { var co

Core data How to update core data info in a SwiftUI view

I have reached an impasse. I would like to display data from CoreData to be edited and then update it back into the database. There doesn't seem to be any way to do this but it is such a basic operation I'm sure the problem is on my end. Here's the code I have import SwiftUI import CoreData struct CustomerEditView: View { @Environment(\.managedObjectContext) var context @State var firstName = "" @State var lastName = "" @State var phone = ""

Core data Items aren't updated in UI after updating them in CoreData

I have List of items and fetch them from CoreData @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)], animation: .default) private var items: FetchedResults<Item> var body: some View { List { ForEach(items) { item in Text("Item at \(item.timestamp!, formatter: itemFormatter)") } } } I try to upate all items but UI shows old values

Core data Setting a property value on each of the results in a FetchedResults set

On my Core Data Entity "Book" i have a boolean property, 'wasViewed' (NSNumber numberWithBool) that tells me if the Book was "viewed". I would like to implement a sort of "reset" this property for all my NSManagedObjects "Book". So that I can set them all to NO between sessions. I use an NSPredicate to retrieve all the Books like this: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"wasViewed == %@", [NSNumber numberWithBool:YES]]; // code for setting entity, request etc... NSMut

Core data Core Data: avoiding retain cycles in to-many relationships

I'm still learning my way through iOS development and working with Core Data and have just come across retain cycles. It is my understanding from reading the Core Data Programming Guide that after you're done working with a relationship, you use the managed object context method refreshObject:mergeChanges to ensure that the retain cycle is broken. So lets say I have a to-many relationship between a Department and its Employees, and in my code I access the employees relationship from department

Core data how does CoreData manage class relationship creation?

I have an entity class, correctly defined in a managed context. This class has a one-to-many relationship with another class. Xcode 4 graphic facilities correctly created the derived classes, and the relationship is represented by a NSSet. I am wondering how the creation of the relation classes is managed. I mean, for creating the main entity I am using the NSManagedObject *newEntity = [NSEntityDescription insertNewObjectForEntityForName:@"EntityName" inManagedObjectContext:context]; But w

Core data Core Data warning: "Version hash information not available for all models"

I get this warning for my xdatamodeld file: "Version hash information not available for all models". How do I get rid of this? I've also started to get a crash at startup when I install the app as new ... wonder if they're related? This is the crash: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Cannot create an NSPersistentStoreCoordinator with a nil model'

Core data Core Data doesn't save objects and is slow

I'm working with Core Data for the first time, with the Stanford iOS app development course as a guide. I pretty much copied the code from the demo app (of course I adjusted it to my needs), but I'm having two problems currently. My app is a map view which on the tap of a button presents a modal view controller. This modal view checks whether a UIManagedDocument was created. If not, it creates one and inserts the data. This data is coming from a property list (258 items, so nothing too excessiv

Core data Problems casting NSManagedObject to subclass type

I'm using custom classes for my CoreData stack. Class properties are set properly in the model. There's some points in the app that are abstracted to use setValue... on an NSManagedObject, but I have a few cases where that fails with an NSInvalidArgumentException, specifically when setting a related object; error indicates it wants the specific type, and it's' getting an NSManagedObject, hence the error. So, I thought I would just take the short route and cast my instance prior to the offending

Core data How do you get a new Core Data Entity attribute to be reflected in the NSManagedObject for that Entity?

I'm trying to implement a getter on one of my db classes. But when I execute the following line of code, where "obj" is an NSManagedObject: return [obj valueForKey:@"activationData"]; I get the following NSUnknownKeyException: '[ valueForUndefinedKey:]: the entity Blueprint is not key value coding-compliant for the key "activationData".' I just recently added a String attribute named "activationData" to my "Blueprint" entity using Xcode. But when I run the app the NSManagedObject that repr

Core data Core Data relationship delete rule - Nullify + Cascade

Entities: Video Playlist Item Playlist Relationships: Video is optional to-many to Playlist Item and the delete rule is nullify Playlist is to-many to at least one Playlist Items and the delete rule is nullify Playlist Item is required to-one for Video and the delete rule is nullify Playlist Item is required to-one for Playlist and the delete rule is nullify In the Playlist entity, I have not exposed the playlistItem relationship / set. Instead I have a transient undefined attribute call

Core data Unable to read back from an existing Core Data database

Can anyone help me here. I am really stuck. In my code if no file exists in the Documents location; I create the store, put the data in it and read back from it. This works fine. However, if a file already exists in that location I am unable to read back from it. I have tried a lot, but am really unsure why it is not working. Some times (very few actually), the very same code will work but the other times it wouldn't. Here is the code. When it doesn't work, the debug message 'End of useDocumen

Core data Incompatible managed object model

I'v built the app, with a working datamodell with one entity. The managedObjectContext works fine with the arrayController, and a TableView. A pretty straightforward, and common setup. There's almost no code yet, I'm just trying to play a bit with coredata. The problem is, when I change the modell, for example add a new entity, it no longer compatible, end show two errors while loading the app. here are the errors: The managed object model version used to open the persistent store is incompatib

Core data iCloud Time out. (using iCloud + Core Data + Magical Record

I started an app test to use Core Data and iCloud (using Magical Records). After a lot of troubles to configure Provisioning Profiles and Entitlements, the app finally runs. After a while the app crash and throw this message:: 2012-12-31 03:42:07.079 iCloudTest[252:1103] -[PFUbiquitySafeSaveFile waitForFileToUpload:](268): CoreData: Ubiquity: <PFUbiquityPeerReceipt: 0x1cd5a420>(0) permanentLocation: <PFUbiquityLocation: 0x1cd57b30>: /private/var/mobile/Library/Mobile Documents/MA5B

Core data NSFetchedResultsController: keep sort order same as IN predicate

I have a list of uids, and I need to get Core Data objects with those uids: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid IN %@", uids]; [request setPredicate:predicate]; Now, I want to keep the objects in the same order as the listed uids. So if the array is [3, 1, 2], then I want the returned objects to be in that order as well. Not setting an sort descriptor isn't an option with NSFetchedResultsController, so what should I set the sort descriptor to?

Core data How do you clear NSManagedObjectContext cache?

I am running into an issue where I am using iCloud and CoreData. When I update my core data database on one device, iCloud syncs the data to my second device correctly. However, lets say I have the app running on both devices before I make the core data change. My second device has already made an NSFetchRequest (lets say its called fetchRequest1). After the import from iCloud was successful on my second device, calling the same request again from fetchRequest1 returns the all of my new data (a

Core data Setting predicate based on multiple entities using core data

I have two tables oldaddress and newaddress with common field personID. I have to get details of personID from newaddress which exists in oldaddress also. How to set entity and predicate for the same in core data? equivalent query is select a.personID from new address a, oldaddress b where a.personID=b.personID

Core data Core data relationship confusion

I'm making a core data model, and I have a Client entity that has a to-many relationship to an Appointment entity. An Appointment can turn into a Transaction (if it has been paid for etc.), and I need to keep track of the Appointments of Clients that have turned into Transactions (where Transaction is an entity along with other attributes). A Client can have multiple Transactions, and a Transaction can have multiple Clients (optional). If I put a relationship between Transaction and Client, then

Core data Assigning fetched NSManagedObject to a property

This question may seem long, but I'm sure it's relativity simple for Core-Data experts. Showing the configuration made this Question long. Thanks! In CoreData I have a User entity and an NSManagedObject subclass (User.h/.m) created from that entity. Not sure if it's relevant, but I'm using remote Database with Stackmob. Here is what my fetch request looks like in Review.m: Fetch Request: -(NSArray *)fetchRequest { NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEn

Core data What is the correct way to delete a UIManagedDocument?

I can't seem to find any reliable documentation that explains the correct procedure for deleting a UIManagedDocument, and in particular one where the iCloud options have been turned ON. I understand that this option would delete the file at this fileURL. And this would appear to be fine if iCloud is not being used. [[NSFileManager defaultManager] removeItemAtURL:fileURL error:&error]; If iCloud is being used then CoreData creates files all over the place, including in /Document/CoreDat

Core data UIManagedDocument Creation in ViewDidLoad

After some research I am still unsure on when / how I should create my UIManagedDocument. @interface ViewController () @property (strong, nonatomic) UIManagedDocument *document; @end @implementation ViewController - (void) viewWillAppear:(BOOL)animated { [super viewWillAppear:YES]; NSFileManager *fileManager = [NSFileManager defaultManager]; NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject]; NSString *documentName = @"MyDo

Core data iOS - NSPredicate string.length always evaluates to 0 when string starts with arithmetic operators + - * /

I have a simple method that uses NSPredicate to return the number of rows where comments.length > 0. Problem is, I found that when the Comment column starts with + - * or /, the length property always evaluates to 0, and thus the row is excluded from the count. I opened the table in SQLite browser and verified the column is a VARCHAR. Using a SQLite query to check string length works just fine (LENGTH(ZComments) > 0), so this must be a CoreData issue. Here is my function... -(int)getComment

Core data RestKit Combine Managed Objects with Non-Managed Objects

I am attempting to use a NSManagedObject as a response class in my requests, but I have relationships that I need saturated as well that I do not want managed because they change far more frequently. I have attempted to use just plain NSObject's along with transient relationships to NSManagedObject's, but either approach ends up with empty relationships (the transient or NSObjects don't get saturated). Here is the object I want saturated from the request and stored in SQLite: @interface Car :

Core data Predicate subquery for products associated by tag

I have a datamodel in core data as such: Store <--->> Product <<--->> Tag I'm looking to create a query that matches products based on their associated tags. A typical use scenario would be you choose to search storeA and output storeB. By selecting storeA a list of storeA products is presented. Let's say you pick productA from the list which brings you to a second viewcontroller. That second viewcontroller lists all relating productB's (because earlier you set storeB as

Core data Update Core Data store location to support App Groups

I have an app already in the App Store that uses core data to save data. Now, when iOS 8 is about to come out I wanna add a widget to it, thus I must use App Groups to share data between the binaries. One problem though - I need to change the store location to support App Groups to all the existing users. I wrote the following code, trying to move the store to the new path: // Returns the persistent store coordinator for the application. // If the coordinator doesn't already exist, it is create

Core data NSPredicate Boolean Value Reversed

This is really weird. Here is the predicate I am using to get a "list" with selected property is set to NO: [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"selected == %@", @(NO)]] However the result is an object with the selected property = 1. What am I doing wrong? Update: The selected property was not saved in the first place because I set it in didSave callback. I "re-save" the object but for some reasons the selected property is no longer updates and when I checked the ha

Core data Referencing class-level property from initializer

I have an NSManagedObject subclass with an initializer like this: class Item: NSManagedObject { convenience init(managedObjectContext: NSManagedObjectContext) { let entityDescription = NSEntityDescription.entityForName(preferredEntityName, inManagedObjectContext: managedObjectContext) ... } class var preferredEntityName: String { fatalError("This property must be overridden.") } } Compiler says that Item does not have a member named preferredEntityNa

Core data Core Data "garbage collection"

Does CoreData provide something akin to garbage collection (or reference counting) so that entities can be automatically removed from the persistent store if they are not referenced by other entities? Generally, entities are "root entities". Once created they will exist until explicitly removed. However, I would like to label some entities as not being root entities. These should only exist provided another entity references them that is ultimately referenced by a root entity. As a concrete

Core data Do I need any iCloud settings before using Ensembles for CoreData & iCloud syncing?

I'm developing an app which uses CoreData and is already released. I'm trying to add syncing feature using iCloud and Ensembles 1.x. I added codes which are told in the readme, but syncing doesn't happen. The debug log says it can't leech to ensemble. I enabled iCloud for the project, but only for Key-value storage which is used for another purpose. Do I need to enable other services such as iCloud Documents or CloudKit? Also, I have this line like sample codes do, and wondering ubiquityContai

Core data NSFetchedResultsController update when relationship updates?

Imagine I have a data model that has 2 entities: Movie and Genre. A Movie can belong to many Genres, as a Genre can have many Movies. Now. I want to have a NSFetchedResultsController that observes the Genre entity (using the genre's name as a sectionNameKeyPath) Say I import some data, and a Genre gets a Movie added to it during the import. The question is: Will the NSFetchedResultsController delegate (controllerWillChangeContent: , etc.) methods be called (because the Genre.movies.count

Core data Setting Up CoreData with SceneDelegate - unknown identifier 'window' error - iOS 13 onwards

I was trying to use the official apple documentation for Core Data. Found here. I also ran into a question which was related to my issue, right here on stack. I ran into an issue where, it kept saying that 'window' is not available in the context of AppDelegate. This is the very basic step as per the official documentation. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { if let roo

  1    2   3   4   5   6  ... 下一页 最后一页 共 9 页