Menu
  • HOME
  • TAGS

Error adding CoreData to existing project

ios,objective-c,cocoa,core-data

In this method, - (NSPersistentStoreCoordinator *)persistentStoreCoordinator // Create the coordinator and store _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; Change to this: NSError *err; if ([[NSFileManager defaultManager] createDirectoryAtURL:[[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Models/"] withIntermediateDirectories:YES attributes:nil error:&err]) { NSURL *storeURL = [[self applicationDocumentsDirectory]...

Passing data - Swift

ios,swift,core-data,store-data

I would recommend you to use CoreData for this, and yes, you can access this data anywhere in the app. Explaining how to implement CoreData can end up in quite a big answer though! Instead I will recommend you to watch the following video from a Stanford course on iOS...

Property 'package_number_7' not found on object of type 'User *' after Lightweight Migration

ios,objective-c,xcode,core-data,xcode6

Please check your user class header file , if you miss "package_number_7" to declare.

How to use reflection with Core Data and Swift

ios,swift,core-data,reflection

I believe that this code can help you. I wrote this extension to make a dictionary from a NSmanagedObject and it accesses all attributes and values of the object. extension NSManagedObject { func toDict() -> Dictionary<String, AnyObject>! { let attributes = self.entity.attributesByName.keys let relationships = self.entity.relationshipsByName.keys var dict: [String: AnyObject]...

iPad SearchViewController crash _PFArray objectAtIndex beyond bounds

ios,objective-c,ipad,core-data,uisearchresultscontroller

So I think I found a solution. After playing with breakpoints in my TableViewController, I notice that the method which was crashing when taping on the searchBar was cellForRowAtIndexPath - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ItemCell *cell = [self.tableView dequeueReusableCellWithIdentifier:ItemCellIdentifier forIndexPath:indexPath]; Item *item = nil; if (self.searchDisplayController.active) { item...

Core Data sort descriptor with NSDate, iOS with Swift

ios,swift,core-data

To fetch all objects satisfying some condition you don't need a sort descriptor but a predicate, for example: let predicate = NSPredicate(format: "timeStamp < %@", date) fetchRequest.predicate = predicate You need a sort descriptor to get the objects in a specified order, for example: let sectionSortDescriptor = NSSortDescriptor(key: "timeStamp", ascending:...

Full CoreData uploading (backup) to iCloud Drive and restore if need

ios,xcode,core-data,icloud,cloudkit

Nothing for you to do. Just enable iCloud and it will always be backed up and restorable automatically. See Enable iCloud with Core Data. It's really simple....

iOS Core Data concurrency and other background queues

ios,multithreading,core-data,dispatch-async

It might look a bit complicated buy in practice it's probably the simplest and most well structured approach. Technically you can use only 2 queues (really threads) and NSConfinementConcurrencyType - assuming that you do only have 1 background thread, which your diagram isn't 100% clear on - but it actually...

Is it possible to do fetch and save in Private context,Without notifying anything to main context.?

ios,core-data

Different managed object contexts are not automatically aware of changes made by each other. If you fetch the same object in two contexts, change it in one, and save changes, the other context will not know about the new values unless you merge the changes somehow. That means it has...

two arrays from NSFetchedResultsController swift

ios,swift,core-data,nsfetchedresultscontrolle

You have to call performFetch() before the fetched results controllers's fetchedObjects will change. Instead, you might just use a filter. let frequent = fetchedObjects.filter() { $0.frequent } let infrequent = fetchedObjects.filter() { !$0.frequent } ...

Swift - Storing and retrieving data [closed]

ios,swift,core-data,nsfetchrequest,store-data

You have 4 options: 1) NSUserDefaults - Good for small amounts of data 2) Store on file system using NSArchiver. 3) SqlLite - Good for larger amounts of data. 4) CoreData - Stores object graphs. Very advanced but steep learning curve. For details on all these methods watch the persistence...

Convert NSValue to NSData and back again, with the correct type

objective-c,core-data,nsdata,nsvalue

Use NSKeyedArchiver to save the items and NSKeyedUnarchiver to restore the object. The object must conform to NSCoding and in the case of a collection all contained items must also conform to NSCoding. See the Apple documentation of NSKeyedArchiver and NSCoder...

NSFetchedResultsController section grouping by relation

ios,swift,core-data

no the grouping must happen on a key on the entity. so use a transient property or a fetched property to get the relation and make it a key in your case.. e.g. make all POST objects have a key 'postToGroupBy' or 'postNameToGroupBy or whatever so the post and all...

Crashing after lightweight Core Data migration

ios,core-data

I tried again from scratch and instead of renaming the variable, I created new one. This time app didn't crashed. I am sorry it is not real answer but it helped me to move on. Lessons I learned: Do not confuse Core Data Model Identifier in Xcode inspector and renaming...

this class is not key value coding-compliant for the key itemname

ios,objective-c,iphone,core-data,ios7

You need to send the NSManagedObject instance to your next view controller, not just a single String -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([[segue identifier] isEqualToString:@"EditItemSegue"]) { NSIndexPath *indexPath = [self.tableView indexPathForCell:sender]; Item *item = [[self fetchedResultsController]objectAtIndexPath:indexPath]; NextVCClass *destination = (NextVCClass *)segues.destinationViewController; destination.managedObjectContext=self.managedObjectContext; destination.toDoItem=item; } } You...

NSManagedObject subclass' category equivalent in Swift?

ios,swift,core-data

A Swift extension is the right way to define additional methods for NSManagedObject subclasses. You can put the extension into a separate file (e.g. "BookExtensions.swift") so that they are not overwritten when "Book.swift" is recreated in Xcode.

xCode 6.3.2 Crash [UIViewController .cxx_destruct]

objective-c,xcode,core-data,memory-management

// Code which caused [UIViewController .cxx_destruct] Article *article = [Article new]; // Fixed with this NSManagedObject *article = [NSEntityDescription insertNewObjectForEntityForName:@"Article" inManagedObjectContext:context]; ...

Creating a Mapping Model by code instead of XCode

ios,objective-c,xcode,core-data

A mapping model is for heavy migration. Heavy migration does not work well on iOS (or at all). Instead, you should be doing a lightweight migration. That will be faster and will work on iOS correctly. As for creating a mapping model in code, you cannot. It can only be...

UIActivityIndicatorView (spinner) wont show or stop after loading remote json data

json,swift,core-data

Use the completion handler to show hide the spinner: func updateSeedJsonFromServer() { self.startSpinner() NSURLSession.sharedSession().dataTaskWithURL(NSURL(string:seedLoadURL)!, completionHandler: { (data, response, error) -> Void in //on the first line self.stopSpinner() }).resume() ...

RestKit throws NSInternalInconsistencyException upon PUT request

ios,swift,core-data,restkit

Curiously now, the entity and the self.entity object both have the same debug description. The addresses of the entity descriptions must be different. This usually happens when you tamper with the managed object context that RestKit is using so the entities that are compared come from 2 different contexts...

how to have existing data in coredata ENTITY before the app launches

ios,core-data,settings,default-database

CoreData doesn't provide any facility to create default tuples when the database is setup. SO, for the user to see some default values which he can change the state in future and see the desired changed value whenever he logs in - he needs to create the database tuples with...

Swift CoreData compare string with entities

ios,swift,core-data

Your current code fetches ALL the Task objects, but compares the id of only the first one in the resulting array (objects). So duplicates elsewhere in this array will not be detected. Restructure your code slightly, to check first whether there is an existing Task with the relevant id. Use...

Retrieving Entities from Core Data: Printing properties gives me incomplete/unwanted results?

objective-c,core-data,printing,attributes

Assuming your CXStellarObject object is a custom subclass of NSManagedObject, you need to override the description method for that object and write it to return formatted info about your managed object. Something like this: -(NSString *) description; { NSMutableString *result = [[NSMutableString alloc] init]; [result appendFormat: @" descriptor = %@\n",...

Functions for fetching and saving data in an NSManagedObject class

ios,swift,core-data

var userInstance:User = User() creates a user object without using the designated initializer, and that causes the error message. If the only reason to create this User object is to call the saveUser() and fetchUser() methods then it is the wrong approach, and you should define the methods as class...

Should I reset context from its own thread?

ios,multithreading,core-data

Any calls to a context must be on the queue associated with that context. If you are calling reset, it must be from the queue associated with the thread. Coming from an arbitrary thread, call it in the block. You can test this and other questions like this by turning...

NSFetchRequest to retrieve Every Student's Maximum Test Score for Every Subject in CoreData Entity

ios,uitableview,core-data,nspredicate

Okay, here is what I came up with. Hope this helps others out: I parsed the Managed Objects into NSMutableArrays based upon the "class" (race in my case). Then I used put each NSM Array into a NSMutableDictionary where an index acted as the key. This dictionary and the arrays...

How can I convert Int32 to Int in Swift?

swift,core-data,int,type-conversion

The error is your ? after valueForKey. Int initializer doesnt accept optionals. By doing myUnit.valueForKey(“theNUMBER”)?.intValue! gives you an optional value and the ! at the end doesnt help it. Just replace with this: return Int(myUnit.valueForKey(“theNUMBER”)!.intValue) But you could also do like this if you want it to be fail safe:...

Get fields from NSArray with CoreData content

ios,xcode,swift,core-data

You will need to loop your array of results and cast each result as the NSManagedObject you retrieved, in you case Radar if results.count > 0 { for result in results { if let r = result as? Radar{ //now you can access the properties of Radar in r println(r.descr)...

Save Image as local file or as binary data IOS

ios,uitableview,swift,core-data

Thanks for the gist, I have some suggestion regarding how you could achieve it in little bit cleaner way. This is of course untested code and should only be used as inspiration. The idea is to have a cleaner cellForRowAtIndexPath and try working with list of models where the data...

Core Data Scalar error only on some devices

ios,swift,core-data

If the Core Data type is Integer 64 then should declare the property as Int64 (or let Xcode create the managed object subclass). Int can be 32 bit or 64 bit, depending on the processor architecture. Alternatively, define the property as NSNumber* instead of a scalar property. Of course you...

Which is a better way: retrieve images from AWS S3 or download it and store locally in a temp folder to be displayed?

objective-c,core-data,amazon-web-services,amazon-s3,awss3transfermanager

It depends on how you use them. If your app is going to retrieve the images similiar to instagram, or twitter, it's good to download them as the user requested the images via the app. If once the images are retrieved, the application going to use the images again and...

One to Many remove Object not deleting object on many entity

ios,core-data

removeGame and removeGameObject are methods on the Activity entity, so why would you think that they would delete a Game object? They do exactly what they say, the remove the Game from this Activity - removing the reference, but they don't actually delete the Game object. These methods are a...

How do I compare the value of password stored in CoreData with user input?

swift,core-data,ios8,xcode6

Your almost correct, and only one more step needed to make magic happen. Thats to set predicate to request like following request1.predicate = predicate ...

Core Data and a UIActivityViewController

objective-c,core-data,nsmutablearray,nsarray,uiactivityviewcontroller

- (IBAction)ShareItem:(id)sender { NSString *textToShare = @"This is just some random text I put here"; NSURL *myWebsite = [NSURL URLWithString:@"http://www.martylavender.com/"]; NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Item"]; fetchRequest.resultType = NSDictionaryResultType; NSError *error = nil; NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; NSMutableArray *itemNames = [results valueForKey:@"itemname"]; NSString *names = [itemNames...

iOS App groups - shared CoreData fails to open

ios,objective-c,core-data,watchkit,ios-app-group

After a lot of searching, I found that the storeURL would change (randomly) between these two: file:///var/mobile/... file:///private/var/mobile/... I used URLByResolvingSymlinksInPath on the URL as specified in the following answer, and incredibly, it fixed it: What does the /private prefix on an iOS file path indicate? I'm assuming this is...

How can I populate a tableView with an NSSet? (swift)

ios,uitableview,swift,core-data

Is there a particular order that is sortable that you want the table view's contents to be displayed in? Instead of directly accessing the data structure "Brand", you could have a data manager that manipulates the data in a uniform fashion. You could keep all of the Brand information in...

Save NSUndoManager transactions one by one

ios,core-data,nsmanagedobjectcontext,nsundomanager

NSUndoManager is not really suited to this task. You can tell it to undo or redo actions, but you can't inspect those actions or selectively save data in the current undo stack. What I've done in the past is create my own queue of outgoing changes. Whenever changes are saved...

Delete row in TableView and remove the core data - iOS / Swift

swift,core-data,xcode6,delete-row

SOLVED The issue with my delete was not the issue. (NOTE: you do not need the "tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:.Fade)" line in your delete function.) The issue I was originally having was that the slide would work but the user would not be prompt with the delete. Make sure you check your...

Unable to query for date using NSPredicate in Swift

ios,swift,core-data,nspredicate

NSPredicate(format:_:) takes a format string and a list of arguments, but you're passing a simple string. This doesn't work, since this initializer doesn't just call stringWithFormat: on the parameters, but actually looks at the arguments' type information as it's building the predicate. You can use that initializer by passing the...

App crash after hammering button

multithreading,osx,swift,cocoa,core-data

For what it's worth... I managed to fix the issue. It was due to the complexity of my code that I didn't see that one command used to clear the array controller for the generated data interfered with the part where the new data is being added. There was some...

MainPageCollectionViewConrtoller _setViewDelegate:]: unrecognized selector sent to instance 0x7faa7ae39160

ios,swift,core-data,uicollectionview,uicollectionviewcell

Well,I couldn't found the real reason,But it fixed by creating a new project with same content.So it was probably an error in project's configuration.

Core Data One-To-Many Relationship Memory Usage

ios,core-data,memory-management,one-to-many

There are NUMEROUS disadvantages to not specifying an inverse. You will have poorer performance, Core Data will need to work harder and you risk integrity issues. Always, always, always have an inverse relationship. Even if you will never use it, Core Data will. You will not have a memory issue...

IOS/Xcode/Objective C:Load one record from Core Data without loading table first

ios,core-data,executefetchrequest

What is wrong with your code? What doesn't it do? Based on your description, the code you provided does exactly what you are asking. As for your comment about loading a table, you never load a table. Core Data is an object model design. Even when you configure it to...

Core Data, with Swift. Entity query

ios,swift,core-data

You get the number of objects a fetch request would have returned with countForFetchRequest(): func countEntity (name:String, context : NSManagedObjectContext) -> Int { let fetchRequest = NSFetchRequest(entityName:name) var error : NSError? let theNumberOfRecords = context.countForFetchRequest(fetchRequest, error: &error) if theNumberOfRecords == NSNotFound { println("Error: \(error?.localizedDescription)") } return theNumberOfRecords } In the...

Collection View automatically handles large amounts of records?

ios,swift,core-data,ios8,uicollectionview

I use AshFurrow's implementation of a fetched results controller with a collection view. Then when you lazy load your fetched results controller, just set your batch size. - (NSFetchedResultsController *)fetchedResultsController { if (_fetchedResultsController != nil) { return _fetchedResultsController; } NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; // Your added implementation [fetchRequest...

Store Core Data Sqlite in NSLibraryDirectory or NSApplicationSupportDirectory?

ios,sqlite,core-data,path,sync

If doesn't matter for syncing service where you store your data file. But if you will change its location then you have to move your data file of previous users to new location.

Crash: Swift, Adding a new Entity on an already existing Core Data

ios,swift,core-data

Each time you change your data model, you must uninstall your app on the device or on the simulator. Thus, in the next build and run, the updated DB will be loaded. Of course, you lose all the data being loaded in the precedent version.

Saving a Managed Object with a To One type

ios,swift,core-data

To create a one-to-one relationship you can set it from either side. Do this before saving. Thus: selectedFolder.planner = note // or note.folder = selectedFolder Of course, this will only work if you have set up the relationship and reverse relationship correctly in the Core Data model editor....

Core Data - Swift - Catch “keypath not found in entity” error

ios,swift,core-data,error-handling

In Swift, try-catch isn't available. You can switch back to Objective-C, or use a library like this one to add the functionality. That said, your problem can be solved by keeping track of which keys are valid, instead of implementing a try-and-see approach. ...

Exception thrown at predicate

ios,core-data

Thanks for screenshot. My guess is that it's not exactly the NSPredicate problem. Try to change code to this: let predicate = NSPredicate(format: "year_created >= %ld", year) NSDateComponent's year property is NSInteger, so you can't use %@ in format....

Am I approaching concurrency right?

ios,objective-c,core-data,concurrency

I struggled with this same issue not long ago. I've looked for best practice scenarios and found that: You indeed, as you stated, shouldn't violate the one context/thread rule set by Apple. You should normally use completion blocks or notifications with long running operations, whether it's for not making the...

Calling method on object in NSPredicate with Core Data

ios,core-data,nspredicate

If you are fetching position entities with any employees matching meEmployee then you can use a predicate like this: NSPredicate *predicate = [NSPredicate predicateWithFornat:@"ANY employees == %@", meEmployee]; But if the inverse relationship for employees is position, you can achieve the same with: meEmployee.position ...

How can I sort an array from Core Data using a stored integer attribute?

ios,arrays,swift,uitableview,core-data

First, your array with a fetch requests necessary to retrieve the objects is not very efficient. Just use a NSFetchedResultsController and the index paths will automatically point to your objects. In addition, you get great memory and performance optimizations for free. As has been pointed out in the comments, you...

change NSManagedObject parent entity in another version

ios,core-data,nsmanagedobject,core-data-migration,nsmanagedobjectmodel

O.k the solution is quite simple, You make the required changes in the model (change the "anObject" parent entity) Then all you need to do is add a new mapping model, by selecting "New File" -> "Core Data" -> "Mapping Model" Make sure you make the changes in the model...

Storing images to CoreData - Swift

ios,image,swift,core-data,nsdata

Core Data isn't meant to save big binary files like images. Use Document Directory in file system instead. Here is sample code to achieve that. let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String // self.fileName is whatever the filename that you need to append to base directory here. let path...

Ensembles in iOS swift

ios,swift,core-data,ensembles

The following steps describe how you add ensembles with the iCloud + Dropbox filesystem to your project: Add a 'Podfile' to your project with this contents: target :YOUR_TARGET_NAME do platform :ios, '7.0' pod "Ensembles", :git => 'https://github.com/drewmccormack/ensembles.git' pod "Ensembles/Dropbox", :git => 'https://github.com/drewmccormack/ensembles.git' link_with 'YOUR_TARGET_NAME' end Run 'pod install' from your...

How to change attribute type in xcdatamodel?

ios,xcode,core-data,xcdatamodel

This is really complex problem. You can't simply change datatype of an attribute. The error you see means that core data is not able to migrate your data to the new version. 1) Create new model version instead and set new data type there. See https://developer.apple.com/library/ios/recipes/xcode_help-core_data_modeling_tool/Articles/creating_new_version.html 2) Set new model...

UISearchController shows incorrect results

ios,xcode,swift,core-data,uisearchcontroller

I found a solve, I changed my UITableViewController class FirstTableViewController: UITableViewController, NSFetchedResultsControllerDelegate, UITableViewDataSource, UITableViewDelegate, UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate { @IBAction func addNew(sender: UIBarButtonItem) { } let managedObjectContext: NSManagedObjectContext? = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext var fetchedResultsController: NSFetchedResultsController? // MARK: - setting for search...

How do I call the CoreData proxy framework from WatchKit Extension?

ios,iphone,swift,core-data,watchkit

I figured out what the issue was. I had added the files from the framework to the targets of the iphone app and also the watchkit extension, which Apple advises is not allowed anyway and they'll block your app from the store if you try to do it: https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html Anyway...

Getting objects from to-many relationship in Swift Core Data

ios,swift,core-data,one-to-many

Sorry because I'm really tired I couldn't read everything. But from what I've read, you want to get the citizens of a country which should be a NSSet. To get that you can simply do: let contacts = yourArrayOfCountries.flatMap { $0.citizensOfCountry.allObjects as! [Contacts] } According to your comment: let contacts...

Convert ABRecordID to NSNumber always -1

ios,swift,core-data,nsnumber,abpeoplepickerview

In iOS 8, you can browse the contacts without it ever requesting permission to the address book (because you might, for example, allow the user to perform the default action with ever returning actual data to the app). But to actually get the particulars on a contact, you have to...

Why my NSFetchedResultsController loads all rows?

ios,objective-c,core-data,nsfetchedresultscontrolle,nsfetchrequest

I have performed the test again with a simplified app to be sure of the behavior. I have 2 VCs: - in the first one, I fetch all objects (22117) with a fetchBatchSize of 20 and access to the first element of the results - in the second one, I...

Updating Core Data Model using two separate View Controllers

ios,objective-c,uitableview,core-data

I resolved this. Here is what was done. First off there was serious cleanup of files, arrangement, etc. There were some objects, attributes, etc., that didnt make sense. Renaming things helped a lot as I was causing a lot of confusion. There was a one-to-one relationship between my List and...

swift - CoreData inManagedObjectContext is nil

ios,swift,core-data

The only optional you are force unwrapping with ! in the offending line is entity. It follows that entity might be nil. One reason could be that the entity name in your model is not "Article". I usually do not use the entity, but insert the object directly with Apple's...

Does executeFetchRequest:error: return the same object instance every time?

ios,objective-c,core-data

Take a look at the Core Data Programming Guide section on Faulting and Uniquing. To quote: Uniquing Ensures a Single Managed Object per Record per Context Core Data ensures that—in a given managed object context—an entry in a persistent store is associated with only one managed object. The technique is...

Slow UISearchDisplayController with Core Data

ios,iphone,core-data,nsfetchedresultscontrolle,uisearchdisplaycontroller

I ended up using a NSTimer for delaying the shouldReloadTableForSearchString method. searchTimerPopped selector is triggered only if the user stop typing the keyboard for 2 seconds. @property (nonatomic, retain) NSTimer *searchTimer; - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString { if (self.searchTimer) { [self.searchTimer invalidate]; self.searchTimer = nil; } self.searchTimer = [NSTimer scheduledTimerWithTimeInterval:2...

How to prevent swift CoreData crash on uninitialized data

ios,uitableview,swift,core-data

You need to check if the array actually has a value in the given index, to do so you can check the number of elements in the array against the value of the index if indexPath.row < self.newsArray.count { let news = self.newsArray[indexPath.row] } else { //set details to blank...

NSManagedObject in temporary context gets faulted

swift,core-data

The most likely scenario is that your scratchpad managed object context is deallocated, and this is wiping out the managed object. Managed objects are dependent on their context but don't retain them (to avoid retain cycles), so if the context ever disappears, they stop working. Nil values for properties is...

Syntax for loop ManagedObject insertion in swift

ios,swift,core-data

You can use Key-Value coding for managed objects: func insertObject (entityName:String, dico: [String : NSObject]) { let newItem = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext:managedObjectContext!) as! EventList for (key, value) in dico { newItem.setValue(value, forKey: key) } } which can be shortened to func insertObject (entityName:String, dico: [String : NSObject]) { let newItem =...

IOS Use Core Data Only in Specific Parts of an app

ios,api,core-data

Initialize it without a context: NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:myMOC]; NSManagedObject *unassociatedObject = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:nil]; Source: How to Deal with Temporary NSManagedObject instances?...

swift crash when altering UITableViewCells during update

ios,uitableview,swift,core-data

The problem is that your datasource must be consistent with your TableView. When you scroll your TableView, each row will be pulled from your datasource every time they are about to appear on screen. When you call stocks.removeAll(keepCapacity: false), you should also reload your TableView to keep them synced. EDIT:...

Core Data: Save edits to persistent store

ios,core-data

Short answer - yes, it is enough to call save:. As long as the changed object is a member of the receiving managedObjectContext and the call returns YES the save has been done. NSManagedObjectContext neither knows nor cares about its backing store type. NSPersistentStore is the thing that knows about...

Undefined symbols for architecture i386 with EncryptedCoreData

ios,swift,core-data,cocoapods,pod

In pods Xcode project -> build setting, set build for active architecture only to 'NO'

Would this fill the child context with only TemporaryIDs?

ios,objective-c,core-data,concurrency

You can force the conversion to happen early, before you've saved changes, like so: [moc obtainPermanentIDsForObjects:moc.insertedObjects.allObjects error:&error]; As I understand it, the object is already in both contexts. You don't need to retrieve it from the store, as it's cached. You still have the object and could query the store,...

I am trying to use Core Data and load a table view with its contents in order and in sections

ios,swift,core-data,tableview

Take a look here for the approach to read section-wise data - http://www.andrewcbancroft.com/2015/03/05/displaying-data-with-nsfetchedresultscontroller-and-swift/ and here iOS UITableView sections with fetchedResultsController confusion...

Implementing Core Data validation methods in Swift

ios,swift,core-data

The documentation on this is very sparse and there isn't much information about it around the web. Adding here as reference for others what I was able to find via some digging and trail and error. This seems to be working: // Validating the 'name' attribute of NSManagedObject's descendant func...

iOS - Confused about when to use Core Data in my app

ios,database,swift,caching,core-data

Actually, for your scenario I would say that you don't need any persistence in your app, but rather fetch your data from the server every time the app starts and just keep it in memory. There are a lot of apps which are doing it this way and this is...

Cannot configure RestKit with CoreData

ios,objective-c,core-data,restkit

As it turns out in order to use RestKit with CoreData you have to create precompiled header file for your project and add the following line: #import <CoreData/CoreData.h> This issue is discussed here: https://github.com/RestKit/RestKit/issues/1564...

Default NSTimeInterval used by CoreData

ios,core-data,nsdate,nstimeinterval

As stated in the documentation and in comments, the internal NSDate reference date is 1 January 2001, which is what is used by Core Data internally when serializing NSDate objects to the database representation. See Wikipedia's article on epoch. NSDate and CFDate both use the Cocoa epoch time (which dates...

Core Data properties based upon relationships returning NULL

core-data,nspredicate,nsmanagedobject,nsmanagedobjectcontext,relationships

In the block below, you need to assign the team to batting. batting.teams = {your_team_object} Then you will be able to access the team information. You can create another fetch to Core Data using the teamID to retrieve the team object. for (id b in BATTING_UVWXYZ) { Batting *batting =...

Core Data not saving in distribution build

ios,core-data,nsmanagedobjectcontext,testflight

NSAssert does not normally run in a Release Build as NS_BLOCK_ASSERTIONS is defined as part of the standard Xcode template. Or from the docs IMPORTANT Do not call functions with side effects in the condition parameter of this macro. The condition parameter is not evaluated when assertions are disabled, so...

How best to subclass NSManagedObject to provide a set of core methods

ios,objective-c,xcode,core-data,refactoring

The technique is to completely separate the domain/semantic models from the Core Data object graph and storage by subclassing. The superclass deals with your CoreData stuffs, and the important or interesting domain methods are added to the subclass ... but it sounds like you already know all this! There are...

swift - CoreData

ios,swift,core-data

From the information above, it looks like you have't added the class for the entity in configuration of the coredata. Make sure you have mapped class against entity in the configuration of .xcdatamodeld file. You can check the below example. ...

Core Data - check if relationship is nil

ios,objective-c,core-data

This line: Test *test = [results valueForKey:@"quantity"]; isn't doing what you expect, because calling valueForKey on an array returns an array, not a Test object. So test.price is trying to access a property on an array that obviously doesn't exist. You probably want something like: Test *test = [results firstObject];...

How do I access the attribute of a one to many relationship and pass to another tableview?

uitableview,core-data,nsfetchedresultscontrolle,nsmanagedobject

So I read up more on faults and learned that it's actually not an error but more of a unrealized object. It will become a real object when it's called. In my case, I had a one-to-many relationship so entity B was a NSSet in the A.h file. I simply...

Magical Record, cannot save an object: contextDidSave == NO, error = nil

ios,objective-c,iphone,core-data,magicalrecord

Your objects have no changes occurring in the save block. There are two problems I see here. You are creating your new objects in the MR_defaultContext when you need to be creating them in the localContext that is the saving context for your save block. Try this: - (void)updateStorageWithQuizzess:(NSArray *)quizzess...

Core Data inputting numbers > 1.0 error

ios,cocoa,cocoa-touch,core-data,nsnumber

I'm guessing that you have a constraint in your Core Data model. Along with the data type, you can set default values as well as minimum and maximum values. I think you probably have it configured to be between 0 and 1. Update the validation rule in your model and...

Sorting the results of an NSFetchRequest of objects that implement compare:

objective-c,cocoa,core-data,nsfetchrequest,nssortdescriptor

The problem was that I was using a SQLite store, and you can only use modelled properties in a NSFetchRequest that relies on a SQLite store. It was very confusing, as it worked on my tests (I was using an In Memory store) and failed miserably in the App itself....

CoreData :NSFetchedResultsController one to many to many to many relationship

ios,objective-c,core-data,nspredicate

You can use SUBQUERY to build NSPredicates that go deep into "to many" relationships: // Set predicate NSPredicate *requestPredicate = [NSPredicate predicateWithFormat:@"SUBQUERY(genres, $g, ANY $g.movies.name == %@)[email protected] != 0", @"Batman vs Superman"]; [fetchRequest setPredicate:requestPredicate]; UPDATE Based on your updated example, you'll need nested subqueries like this: NSPredicate *requestPredicate = [NSPredicate...

Swift code with multiple NSDateFormatter - optimization

ios,swift,core-data,nsdateformatter

You can create only one instance on NSDateFormatter and use it where you need it: lazy var dateFormatter: NSDateFormatter = { let f = NSDateFormatter() f.locale = NSLocale(localeIdentifier: "en_US_POSIX") f.timeZone = NSTimeZone(abbreviation: "GMT+0:00") f.dateFormat = "dd-MM-yyyy" return f }() ...

What is the Difference between Action Methods of MagicalRecord in iOS

ios,core-data,magicalrecord,actionmethod

After thinking and searching lot i got answer ... I acknowledge that these methods aren't documented very well. However, they follow with the Core Data nested context model fairly well. With MagicalRecord don't use save: on anNSManagedObjectContext. MagicalRecord has all those extra error handling, logging and completion handlers built in....