Search Results

Search found 108 results on 5 pages for 'nsmanagedobjectcontext'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • May a NSManagedObjectContext re-fault objects automatically?

    - by frenetisch applaudierend
    I am trying to create an application which allows background threads to update core data objects while the user might be reading the same data. My approach to this would be to use multiple NSManagedObjectContexts and then before a background thread does a -save: operation, I fetch the object the user is currently working on and fire the fault for all its properties and relationships recursively. This way I have all objects the user could act with in my NSManagedObjectContext without seeing the already updated values. But this can only work if the NSManagedObjectContext cannot decide himself that e.g. memory usage is too high, and starts faulting objects which I do not explicitly reference (other than through the NSManagedObject relationship). So the question is, can the NSManagedObjectContext decide that an object needs to be re-faulted, without intervention from my side? Thanks for your effort, Markus

    Read the article

  • Debugging SIGABRT within NSManagedObjectContext -save:

    - by westsider
    From inside NSManagedObjectContext -save: I am getting this message: Assertion failed: (_Unwind_SjLj_Resume() can't return), function _Unwind_SjLj_Resume, file /SourceCache/libunwind/libunwind-24.1/src/Unwind-sjlj.c, line 326. Program received signal: “SIGABRT”. warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found). This happens when I delete an Experiment object with to-many with Run which has to-many with Sample which has to-one with Data. Experiment also has to-many with Page which has to-many with Display which has to-many to Run. I mention this to point out the cyclical nature of the graph. Here is a simplified graph of model: I had been using Delete Rules but have now switched to "No Action" delete rules in combination with -prepareForDeletion methods for all of these classes. This change made no difference. In both cases, the error message is the same. Interestingly, when I relaunch the app, all the objects that were marked for deletion have been deleted. Also, if an Experiment has no Run objects, then deletion works without incidence. For that matter, deleting a single Run from an Experiment also works. I am hoping that someone has seen something like this and can offer advice on what would cause this. Or, if someone has advice on how to get libXcodeDebuggerSupport.dylib for iOS 4.2.1, that might also be helpful. Update: I followed advice found here and was able to get Xcode to find libXcodeDebuggerSupport.dylib for iOS 4.2.1. But this did not help at all in diagnosing problem - which persists.

    Read the article

  • How to not persist NSManagedObjects retrieved from NSManagedObjectContext

    - by RickiG
    Hi I parse an xml file containing books, for each new node I go: Book *book = (Book*)[NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:managedObjectContext]; To obtain an NSManagedObject of my Core Data Book Entity, I then proceed to populate the managed Book object with data, add it to an array, rinse, repeat. When I am done, I present the list of books to the user. I have not yet executed the save: NSError *error; if (![managedObjectContext save:&error]) { NSLog(@"%@", [error domain]); } The user now selects one of the books, this one I would like to persist, but only this one, all the other books are of no interest to me any more. The Book Entity does not have/or is part of any relationships. It is just a "single" Entity. If I pull the "save lever" every Book object will be persisted and I will have to delete everything but my desired one. How would I get around this challenge, I can't really seem to find that particular use-case in the Core Data Programming Guide, which sort of also bugs me a bit, am I going against best practice here? Thanks for any help given.

    Read the article

  • Why might changes be populated from one NSManagedObjectContext to another without an explicit merge?

    - by Mike Laurence
    I'm working on an object import feature that utilizes multiple threads/NSManagedObjectContexts, using http://www.mac-developer-network.com/columns/coredata/may2009/ as my guide (note that I am developing for iPhone). For some reason, when I save one of my contexts the other is immediately updated with the changes, even though I have commented out my calls to mergeChangesFromContextDidSaveNotification. Are there any reasons the contexts might be merging into one another without an explicit call? Here a log of what's going on: // 1.) Main context is saved with "Peter Gabriel" // 2.) Test context is created, begins with same contents as main context // 3.) Main context is inserted with "Spoon" // 4.) Test context is inserted with "Phoenix" // Contents at this point: CoreTest[4341:903] Artists in main context: ( "Peter Gabriel", "Spoon" ) CoreTest[4341:903] Artists in test context: ( "Peter Gabriel", "Phoenix" ) // 5.) testContext is saved // New contents of contexts: CoreTest[4341:903] Artists in main context: ( "Peter Gabriel", "Phoenix", "Spoon" ) CoreTest[4341:903] Artists in test context: ( "Peter Gabriel", "Phoenix" ) As you can see, the test context is saved midway through, and the main context suddenly has the new objects from the test context, even though I haven't performed the whole NSManagedObjectContextDidSaveNotification/mergeChangesFromContext combo. My understanding is that no changes will ever be merged unless done so explicitly... does anyone know what's going on here?

    Read the article

  • Is NSManagedObjectContext autosaved or am I looking at NSFetchedResultsController's cache?

    - by Andreas
    I'm developing an iPhone app where I use a NSFetchedResultsController in the main table view controller. I create it like this in the viewDidload of the main table view controller: NSSortDescriptor *sortDescriptorDate = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES]; NSSortDescriptor *sortDescriptorTime = [[NSSortDescriptor alloc] initWithKey:@"start" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptorDate,sortDescriptorTime, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; [sortDescriptorDate release]; [sortDescriptorTime release]; [sortDescriptors release]; controller = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:@"date" cacheName:nil]; [fetchRequest release]; NSError *error; BOOL success = [controller performFetch:&error]; Then, in a subsequent view, I create a new object on the context: TestObject *testObject = [NSEntityDescription insertNewObjectForEntityForName:@"TestObject" inManagedObjectContext:context]; The TestObject has several related object which I create in the same way and add to the testObject using the provided add...Objects methods. Then, if before saving the context, I press cancel and go back to the main table view, nothing is shown as expected. However, if I restart the app, the object I created on the context shows in the main table view. How come? At first, I thought it was because the NSFetchedResultsController was reading from the cache, but as you can see I set this to nil just to test. Also, [context hasChanges] returns true after I restart. What am I missing here?

    Read the article

  • NSManagedObjectContext returning nil iphone

    - by harekam_taj
    Hey, I created a class ServerModel for my app and in it I want to make a connection to the Sqlite database I have on the device, but anytime I go to check my NSManagedObjectContext it is returning null. While the same work well in my other class RootViewController In my appdelegate I am doing rootViewController.managedObjectContext = self.managedObjectContext; serverModel.managedObjectContext = self.managedObjectContext;

    Read the article

  • NSManagedObjectContext returns YES for hasChanges when there are none

    - by JK
    I created a separate NSManagedObjectContext on a separate thread to perform some store maintenance. However, I have noticed that the context returns YES for hasChanges as soon as a managed object in it is even referenced e.g. NSString *name = managedObject.name; This context is created and used exclusively in 1 method. Why is it returning has changes, when there there are none?

    Read the article

  • NSFetchedResultsController: using of NSManagedObjectContext during update brings to crash

    - by Kentzo
    Here is the interface of my controller class: @interface ProjectListViewController : UITableViewController <NSFetchedResultsControllerDelegate> { NSFetchedResultsController *fetchedResultsController; NSManagedObjectContext *managedObjectContext; } @end I use following code to init fetchedResultsController: if (fetchedResultsController != nil) { return fetchedResultsController; } // Create and configure a fetch request with the Project entity. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Project" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; // Create the sort descriptors array. NSSortDescriptor *projectIdDescriptor = [[NSSortDescriptor alloc] initWithKey:@"projectId" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:projectIdDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Create and initialize the fetch results controller. NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:nil]; self.fetchedResultsController = aFetchedResultsController; fetchedResultsController.delegate = self; As you can see, I am using the same managedObjectContext as defined in my controller class Here is an adoption of the NSFetchedResultsControllerDelegate protocol: - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { // The fetch controller is about to start sending change notifications, so prepare the table view for updates. [self.tableView beginUpdates]; } - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { UITableView *tableView = self.tableView; switch(type) { case NSFetchedResultsChangeInsert: [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeUpdate: [self _configureCell:(TDBadgedCell *)[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; break; case NSFetchedResultsChangeMove: if (newIndexPath != nil) { [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; } else { [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade]; } break; } } - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type { switch(type) { case NSFetchedResultsChangeInsert: [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; break; } } - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { [self.tableView endUpdates]; } Inside of the _configureCell:atIndexPath: method I have following code: NSFetchRequest *issuesNumberRequest = [NSFetchRequest new]; NSEntityDescription *issueEntity = [NSEntityDescription entityForName:@"Issue" inManagedObjectContext:managedObjectContext]; [issuesNumberRequest setEntity:issueEntity]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"projectId == %@", project.projectId]; [issuesNumberRequest setPredicate:predicate]; NSUInteger issuesNumber = [managedObjectContext countForFetchRequest:issuesNumberRequest error:nil]; [issuesNumberRequest release]; I am using the managedObjectContext again. But when I am trying to insert new Project, app crashes with following exception: Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-984.38/UITableView.m:774 Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (4) must be equal to the number of rows contained in that section before the update (4), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted).' Fortunately, I've found a workaround: if I create and use separate NSManagedObjectContext inside of the _configureCell:atIndexPath: method app won't crash! I only want to know, is this behavior correct or not?

    Read the article

  • Using Core Data Concurrently and Reliably

    - by John Topley
    I'm building my first iOS app, which in theory should be pretty straightforward but I'm having difficulty making it sufficiently bulletproof for me to feel confident submitting it to the App Store. Briefly, the main screen has a table view, upon selecting a row it segues to another table view that displays information relevant for the selected row in a master-detail fashion. The underlying data is retrieved as JSON data from a web service once a day and then cached in a Core Data store. The data previous to that day is deleted to stop the SQLite database file from growing indefinitely. All data persistence operations are performed using Core Data, with an NSFetchedResultsController underpinning the detail table view. The problem I am seeing is that if you switch quickly between the master and detail screens several times whilst fresh data is being retrieved, parsed and saved, the app freezes or crashes completely. There seems to be some sort of race condition, maybe due to Core Data importing data in the background whilst the main thread is trying to perform a fetch, but I'm speculating. I've had trouble capturing any meaningful crash information, usually it's a SIGSEGV deep in the Core Data stack. The table below shows the actual order of events that happen when the detail table view controller is loaded: Main Thread Background Thread viewDidLoad Get JSON data (using AFNetworking) Create child NSManagedObjectContext (MOC) Parse JSON data Insert managed objects in child MOC Save child MOC Post import completion notification Receive import completion notification Save parent MOC Perform fetch and reload table view Delete old managed objects in child MOC Save child MOC Post deletion completion notification Receive deletion completion notification Save parent MOC Once the AFNetworking completion block is triggered when the JSON data has arrived, a nested NSManagedObjectContext is created and passed to an "importer" object that parses the JSON data and saves the objects to the Core Data store. The importer executes using the new performBlock method introduced in iOS 5: NSManagedObjectContext *child = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; [child setParentContext:self.managedObjectContext]; [child performBlock:^{ // Create importer instance, passing it the child MOC... }]; The importer object observes its own MOC's NSManagedObjectContextDidSaveNotification and then posts its own notification which is observed by the detail table view controller. When this notification is posted the table view controller performs a save on its own (parent) MOC. I use the same basic pattern with a "deleter" object for deleting the old data after the new data for the day has been imported. This occurs asynchronously after the new data has been fetched by the fetched results controller and the detail table view has been reloaded. One thing I am not doing is observing any merge notifications or locking any of the managed object contexts or the persistent store coordinator. Is this something I should be doing? I'm a bit unsure how to architect this all correctly so would appreciate any advice.

    Read the article

  • Reasons for NSManagedObjectMergeError error on [NSManagedObjectContext save:]

    - by ross-kimes
    I have a application that combines threading and CoreData. I and using one global NSPersistentStoreCoordinator and a main NSManagedObjectContextModel. I have a process where I have to download 9 files simultaneously, so I created an object to handle the download (each individual download has its own object) and save it to the persistentStoreCoordinator. In the [NSURLConnection connectionDidFinishLoading:] method, I created a new NSManagedObject and attempt to save the data (which will also merge it with the main managedObjectContext). I think that it is failing due to multiple process trying to save to the persistentStoreCoordinator at the same time as the downloads are finishing around the same time. What is the easiest way to eliminate this error and still download the files independently? Thank you!

    Read the article

  • Core Data performance deleteObject and save managed object context

    - by Gary
    I am trying to figure out the best way to bulk delete objects inside of my Core Data database. I have some objects with a parent/child relationship. At times I need to "refresh" the parent object by clearing out all of the existing children objects and adding new ones to Core Data. The 'delete all' portion of this operation is where I am running into trouble. I accomplish this by looping through the children and calling deleteObject for each one. I have noticed that after the NSManagedObjectContext:Save call following all of the deleteObject calls is very slow when I am deleting 15,000 objects. How can I speed up this call? Are there things happening during the save operation that I can be aware of and avoid by setting parameters different or setting up my model another way? I've noticed that memory spikes during this operation as well. I really just want to "delete * from". Thanks.

    Read the article

  • Problem with entityForName & ManagedObjectContext when extending tutorial material

    - by Martin KS
    Afternoon all, I tried to add a second data entity to the persistent store in the (locations) coredata tutorial code, and then access this in a new view. I think that I've followed the tutorial, and checked that I'm doing a clean build etc, but can't see what to change to prevent it crashing. I'm afraid I'm at my wits end with this one, and can't seem to find the step that I've missed. I've pasted the header and code files below, please let me know if I need to share any more of the code. The crash seems to happen on the line: NSEntityDescription *entity = [NSEntityDescription entityForName:@"Album" inManagedObjectContext:[self managedObjectContext]]; There is one other line in the code that refers to galleryviewcontroller at the moment, and that's in the main application delegate: galleryViewController.managedObjectContext = [self managedObjectContext]; GalleryViewController.h #import <UIKit/UIKit.h> @interface GalleryViewController : UIViewController { NSManagedObjectContext *managedObjectContext; int rowNumber; IBOutlet UILabel *lblMessage; UIBarButtonItem *addButton; NSMutableArray *imagesArray; } @property (readwrite) int rowNumber; @property (nonatomic,retain) UILabel *lblMessage; @property (nonatomic,retain) NSMutableArray *imagesArray; @property (nonatomic, retain) NSManagedObjectContext *managedObjectContext; @property (nonatomic, retain) UIBarButtonItem *addButton; -(void)updateRowNumber:(int)theIndex; -(void)addImage; @end GalleryViewController.m #import "RootViewController.h" #import "LocationsAppDelegate.h" #import "Album.h" #import "GalleryViewController.h" #import "Image.h" @implementation GalleryViewController @synthesize lblMessage,rowNumber,addButton,managedObjectContext; @synthesize imagesArray; /* // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { // Custom initialization } return self; } */ -(void)updateRowNumber:(int)theIndex{ rowNumber=theIndex; LocationsAppDelegate *mainDelegate =(LocationsAppDelegate *)[[UIApplication sharedApplication] delegate]; Album *anAlbum = [mainDelegate.albumsArray objectAtIndex:rowNumber]; lblMessage.text = anAlbum.uniqueAlbumIdentifier; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addImage)]; addButton.enabled = YES; self.navigationItem.rightBarButtonItem = addButton; /* Found this in another answer, adding it to the code didn't help. if (managedObjectContext == nil) { managedObjectContext = [[[UIApplication sharedApplication] delegate] managedObjectContext]; } */ NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Album" inManagedObjectContext:[self managedObjectContext]]; [request setEntity:entity]; // Order the albums by creation date, most recent first. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"imagePath" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; [sortDescriptor release]; [sortDescriptors release]; // Execute the fetch -- create a mutable copy of the result. NSError *error = nil; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if (mutableFetchResults == nil) { // Handle the error. } [self setImagesArray:mutableFetchResults]; int a = 5; int b = 10; for( int i=0; i<[imagesArray count]; i++ ) { if( a == 325 ) { a = 5; b += 70; } UIImageView *any = [[UIImageView alloc] initWithFrame:CGRectMake(a,b,70,60)]; any.image = [imagesArray objectAtIndex:i]; any.tag = i; [self.view addSubview:any]; [any release]; a += 80; } } -(void)addImage{ NSString *msg = [NSString stringWithFormat:@"%i",rowNumber]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Add image to" message:msg delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil]; [alert show]; [alert release]; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - (void)viewDidUnload { [super viewDidUnload]; } - (void)dealloc { [lblMessage release]; [managedObjectContext release]; [super dealloc]; } @end

    Read the article

  • iPhone CoreData: How can I track/observe all changes within a subgraph?

    - by D Carney
    I have a NSManagedObjectContext in which I have a number of subclasses of NSManagedObjects such that some are containers for others. What I'd like to do is watch a top-level object to be notified of any changes to any of its properties, associations, or the properties/associations of any of the objects it contains. Using the context's 'hasChanges' doesn't give me enough granularity. The objects 'isUpdated' method only applies to the given object (and not anything in its associations). Is there a convenient (perhaps, KVO-based) was I can observe changes in a context that are limited to a subgraph?

    Read the article

  • How do you delete a core data entry from the detail view?

    - by Sam
    I am working with an app similar to apple's core data recipes sample code. I want to be able to delete the entry from the detail view, much like apple's contacts app. The code below is deleting the 1st entry and not the selected entry. Not sure what I am doing wrong. NSIndexPath *indexPath = [myTableView indexPathForSelectedRow]; NSManagedObjectContext *context = [fetchedResultsController managedObjectContext]; [context deleteObject:[fetchedResultsController objectAtIndexPath:indexPath]]; [myTableView reloadData];

    Read the article

  • How do I copy or move an NSManagedObject from one context to another?

    - by Aeonaut
    I have what I assume is a fairly standard setup, with one scratchpad MOC which is never saved (containing a bunch of objects downloaded from the web) and another permanent MOC which persists objects. When the user selects an object from scratchMOC to add to her library, I want to either 1) remove the object from scratchMOC and insert into permanentMOC, or 2) copy the object into permanentMOC. The Core Data FAQ says I can copy an object like this: NSManagedObjectID *objectID = [managedObject objectID]; NSManagedObject *copy = [context2 objectWithID:objectID]; (In this case, context2 would be permanentMOC.) However, when I do this, the copied object is faulted; the data is initially unresolved. When it does get resolved, later, all of the values are nil; none of the data (attributes or relationships) from the original managedObject are actually copied or referenced. Therefore I can't see any difference between using this objectWithID: method and just inserting an entirely new object into permanentMOC using insertNewObjectForEntityForName:. I realize I can create a new object in permanentMOC and manually copy each key-value pair from the old object, but I'm not very happy with that solution. (I have a number of different managed objects for which I have this problem, so I don't want to have to write and update copy: methods for all of them as I continue developing.) Is there a better way?

    Read the article

  • insertNewObjectForEntityForName: inManagedObjectContext: returning NSNumber bug?

    - by beinstein
    I'm relatively well versed in CoreData and have been using it for several years with little or no difficulty. All of a sudden I'm now dumbfounded by an error. For the life of me, I can't figure out why insertNewObjectForEntityForName:inManagedObjectContext: is all of a sudden returning some sort of strange instance of NSNumber. GDB says the returned object is of the correct custom subclass of NSManagedObject, but when I go to print a description of the NSManagedObject itself, I get the following error: *** -[NSCFNumber objectID]: unrecognized selector sent to instance 0x3f26f50 What's even stranger, is that I'm able to set some relationships and attributes using setValue:forKey: and all is good. But when I try to set once specific relationship, I get this error: *** -[NSCFNumber entity]: unrecognized selector sent to instance 0x3f26f50 Has anyone ever encountered anything like this before? I've tried clean all targets, restarting everything, even changing the model to the relationship in question is a to-one instead of a to-many. Nothing makes any difference.

    Read the article

  • insertNewObjectForEntityForName:inManagedObjectContext: returning NSNumber bug?

    - by beinstein
    I'm relatively well versed in CoreData and have been using it for several years with little or no difficulty. For the life of me, I can't figure out why insertNewObjectForEntityForName:inManagedObjectContext: is all of a sudden returning some sort of strange instance of NSNumber. GDB says the returned object is of the correct custom subclass of NSManagedObject, but when I go to print a description of the NSManagedObject itself, I get the following error: *** -[NSCFNumber objectID]: unrecognized selector sent to instance 0x3f26f50 What's even stranger, is that I'm able to set some relationships and attributes using setValue:forKey: and all is good. But when I try to set one specific relationship, I get this error: *** -[NSCFNumber entity]: unrecognized selector sent to instance 0x3f26f50 I've tried everything from clean all targets, to restarting both mac and iPhone, even editing the model so that the relationship in question is to-one instead of to-many. No matter what I do, the same problem appears. Has anyone ever seen anything like this before?

    Read the article

  • NSUndoManager, Core Data and selective undo/redo

    - by Combat
    I'm working on a core data application that has a rather large hierarchy of managed objects similar to a tree. When a base object is created, it creates a few child objects which in turn create their own child objects and so on. Each of these child objects may gather information using NSURLConnections. Now, I'd like to support undo/redo with the undoManager in the managedObjectContext. The problem is, if a user creates a base object, then tries to undo that action, the base object is not removed. Instead, one or more of the child objects may be removed. Obviously this type of action is unpredictable and unwanted. So I tried disabling undo registration by default. I did this by calling disableUndoRegistration: before anything is modified in the managedObjectContext. Then, enabling undo registration before base operations such as creating a base object the again re-disabling registrations afterwords. Now when i try to undo, I get this error: undo: NSUndoManager 0x1026428b0 is in invalid state, undo was called with too many nested undo groups Thoughts?

    Read the article

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

    - by RickiG
    Hi 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... NSMutableArray *mutableFetchResults = [[[managedObjectContext executeFetchRequest:request error:&error] mutableCopy] autorelease]; This is working just fine, however, now I need to set up a loop, go through each Book object, something like this: for(Book *b in mutableFetchResults) { [b setWasViewed:NO] } Is there a way to perform an action on each element that fits the predicate instead of retrieving it? So instead of executeFetchRequest on a managedObjectContext it could be executeOperationOnFetchRequestResults or something along those lines. Thanks for any input given:)

    Read the article

  • coredata using old file version on device

    - by Martin KS
    This is a follow on from my previous problems here. Resetting the simulator solved all my troubles before, and I've gone on to complete my App. I now have the exact same problem when installing the app onto my iPhone device. It picks up an old version of my database, which doesn't have the second entity in it, and crashes when I try to access the second entity: 2010-04-22 23:52:18.860 albumCloud[135:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Image'' 2010-04-22 23:52:18.874 albumCloud[135:207] Stack: ( 843263261, 825818644, 820669213, 20277, 844154820, 16985, 14633, 844473760, 844851728, 862896011, 843011267, 843009055, 860901832, 843738160, 843731504, 11547, 11500 ) terminate called after throwing an instance of 'NSException' I have two questions: 1) How on earth do I delete my app thoroughly enough from my phone that it removes the old data? (I've so far tried regular app deletion, deleting and then holding home and power for a reboot, cursing at and threatening the app while running it... everything) 2) How do I prevent this happening when my application is in the App store, and I for some reason decide that I want to add another entity to the store, or another attribute to the existing entities? is there an "if x doesn't exist then create it" method?

    Read the article

  • NSFetchedResultsController doesn't fetch up the child-parent moc chain?

    - by Kronusdark
    I cannot find any clarification on this, so it may be a bug. Problem is, I have a series of parent-child Managed Object Context's. When I save on a child context the changes get pushed up to the parent, and I can fetch using a plain old NSFetchRequest. However, if I rely on an NSFetchedResultsController to pull these changes into a sibling context to the first, they do not see them. calling -(void)performFetch: error; doesn't seem to pull the changes either. After a restart of the app, all new data is available. My hypothesis is that NSFetchedResultsController only fetches from its current context and will not follow the chain to the persistent store. Can someone please set me straight here? Am I going to have to use notifications to monitor changes on other contexts? and finally, is this mentioned somewhere in the doc's? I cannot find it for the life of me.

    Read the article

  • Losing NSManaged Objects in my Application

    - by Wayfarer
    I've been doing quite a bit of work on a fun little iPhone app. At one point, I get a bunch of player objects from my Persistant store, and then display them on the screen. I also have the options of adding new player objects (their just custom UIButtons) and removing selected players. However, I believe I'm running into some memory management issues, in that somehow the app is not saving which "players" are being displayed. Example: I have 4 players shown, I select them all and then delete them all. They all disappear. But if I exit and then reopen the application, they all are there again. As though they had never left. So somewhere in my code, they are not "really" getting removed. MagicApp201AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; context = [appDelegate managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *desc = [NSEntityDescription entityForName:@"Player" inManagedObjectContext:context]; [request setEntity:desc]; NSError *error; NSMutableArray *objects = [[[context executeFetchRequest:request error:&error] mutableCopy] autorelease]; if (objects == nil) { NSLog(@"Shit man, there was an error taking out the single player object when the view did load. ", error); } int j = 0; while (j < [objects count]) { if ([[[objects objectAtIndex:j] valueForKey:@"currentMultiPlayer"] boolValue] == NO) { [objects removeObjectAtIndex:j]; j--; } else { j++; } } [self setPlayers:objects]; //This is a must, it NEEDS to work Objects are all the players playing So in this snippit (in the viewdidLoad method), I grab the players out of the persistant store, and then remove the objects I don't want (those whose boolValue is NO), and the rest are kept. This works, I'm pretty sure. I think the issue is where I remove the players. Here is that code: NSLog(@"Remove players"); /** For each selected player: Unselect them (remove them from SelectedPlayers) Remove the button from the view Remove the button object from the array Remove the player from Players */ NSLog(@"Debugging Removal: %d", [selectedPlayers count]); for (int i=0; i < [selectedPlayers count]; i++) { NSManagedObject *rPlayer = [selectedPlayers objectAtIndex:i]; [rPlayer setValue:[NSNumber numberWithBool:NO] forKey:@"currentMultiPlayer"]; int index = [players indexOfObjectIdenticalTo:rPlayer]; //this is the index we need for (int j = (index + 1); j < [players count]; j++) { UIButton *tempButton = [playerButtons objectAtIndex:j]; tempButton.tag--; } NSError *error; if ([context hasChanges] && ![context save:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } UIButton *aButton = [playerButtons objectAtIndex:index]; [players removeObjectAtIndex:index]; [aButton removeFromSuperview]; [playerButtons removeObjectAtIndex:index]; } [selectedPlayers removeAllObjects]; NSError *error; if ([context hasChanges] && ![context save:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } NSLog(@"About to refresh YES"); [self refreshAllPlayers:YES]; The big part in the second code snippet is I set them to NO for currentMultiPlayer. NO NO NO NO NO, they should NOT come back when the view does load, NEVER ever ever. Not until I say so. No other relevant part of the code sets that to YES. Which makes me think... perhaps they aren't being saved. Perhaps that doesn't save, perhaps those objects aren't being managed anymore, and so they don't get saved in. Is there a lifetime (metaphorically) of NSManaged object? The Players array is the same I set in the "viewDidLoad" method, and SelectedPlayers holds players that are selected, references to NSManagedObjects. Does it have something to do with Removing them from the array? I'm so confused, some insight would be greatly appreciated!!

    Read the article

  • Core Data: Deleting causes 'NSObjectInaccessibleException' from NSOperation with a reference to a deleted object

    - by Bryan Irace
    My application has NSOperation subclasses that fetch and operate on managed objects. My application also periodically purges rows from the database, which can result in the following race condition: An background operation fetches a bunch of objects (from a thread-specific context). It will iterate over these objects and do something with their properties. A bunch of rows are deleted in the main managed object context. The background operation accesses a property on an object that was deleted from the main context. This results in an 'NSObjectInaccessibleException', reason: 'CoreData could not fulfill a fault' Ideally, the objects that are fetched by the NSOperation can be operated on even if one is deleted in the main context. The best way I can think to achieve this is either to: Call [request setReturnsObjectsAsFaults:NO] to ensure that Core Data won't try to fulfill a fault for an object that no longer exists in the main context. The problem here is I may need to access the object's relationships, which (to my understanding) will still be faulted. Iterate through the managed objects up front and copy the properties I will need into separate non-managed objects. The problem here is that (I think) I will need to synchronize/lock this part, in case an object is deleted in the main context before I can finish copying. Am I missing something obvious? It doesn't seem like what I'm trying to accomplish is too out of the ordinary. Thanks for your help.

    Read the article

  • NSContextManagedObject - Problem Accessing it

    - by Jacob
    I have tab bar navigation application and The problem is that in my root controller I am able to set its NSContextManagedObject to the app delegates...However when I try to do the same on the other controller the application freezes... This only happens in the ViewDidLoad but thats where I need to set it so I can fetch the data

    Read the article

1 2 3 4 5  | Next Page >