NSObjectInaccessibleException CoreData could not fulfill a fault - still confused - iphone

I see this issue has been asked a bit but all the answers seem to point to the cause being trying to update an object when the context has been deleted. I don't think I'm doing that but I'm getting the error so I'm confused (admittedly, I'm shaky on managing retention and references to begin with).
I have an Entity that holds user preferences as essentially key-value records. One of them is an email address.
UserPreference *prefEmailAddress;
#property (nonatomic, retain) UserPreference *prefEmailAddress;
In my class, in my ViewWillAppear method, I build a fetch request and get a reference to the email address value and set a UI text box to the value. This works fine.
NSArray *prefs = [context executeFetchRequest:request error: &error];
if ([prefs count] > 0) {
prefEmailAddress = [prefs objectAtIndex:0];
[prefEmailAddress setValue:emailAddress.text forKey:#"prefValue"];
}
However, in another method when I try to save the potentially modified text box text back to the object, I get the above crash.
I'm just doing this;
NSLog(#"Addr: %#",emailAddress.text);
// [prefEmailAddress setValue:emailAddress.text forKey:#"prefValue"];
The last line causes the exception. Seems like the prefEmailAddress object should still exist but it apparently doesn't.
Thanks for any hints on this.

I solved mine by removing
[fetchRequest setFetchBatchSize:<INT_VALUE>];
if this is in your code when fetching request.

Related

Bugg with NSDictonary sometimes crashes with "Trying to insert nil" response

I´m having a great deal of trouble with a bugg that in some cases gives the "initWithObjects:forKeys:count:]: attempt to insert nil object from objects[6]'" error message. It´s only occurring around every third trial and in the other cases it works fine. I haven´t debugged buggs that happeds at certain situations so that´s whyI´m asking for help. It might be difficult to find a solution but I would be glad to receive some advice atleast where to start look for the issue and how to debug it?
Basically my app have a method that sends a NSDictonary list with objects to a server. In some cases I want to remove an object if the user have´t chosen anything for that list. Problem is that the server died´t like sending an object with an empty space. So I made a kind of not nice looking work around. Basically The IBaction checks if the Object contains nil. If it contains nil it redirects to a very similar NSDictonary without the Object containing Nil. It woks in some cases but it seems like it sometimes don´t recognize the object containing nil.
Here´s the code in Inaction that redirects the code. I haven´t created a method for inserting anything to the object:#"DefaultCreateImageID" yet so as far as I know it should always be nil.
NSString *Imagestuff= [[NSUserDefaults standardUserDefaults] objectForKey:#"DefaultcreateImageID"];
if ( [[NSUserDefaults standardUserDefaults] objectForKey:#"DefaultcreateImageID"] != ( NSString *) [NSNull null] ){
DataHandler *handler = [DataHandler sharedDatahandler];
handler.authenticateUserDelegate = self;
[handler createActivityNoImage];
NSLog(Imagestuff);
}
else
{
DataHandler *handler = [DataHandler sharedDatahandler];
handler.authenticateUserDelegate = self;
[handler createActivity];
}
Thanks!
If you get an error "Trying to insert nil" then one of the objects you are trying to add to the dictionary is nil. Solution: Don't do that.
Figure out why some item you are trying to add to the dictionary is nil. Then figure out what you want to do in the situation.
To follow up on gnashers729 answer. The problem for me isn't nil but the fact my Inaction fails to reqognize what the object contains.
Here for example I tried to replace nil with a string to reqognize. I get the same problem that my method in some cases recognize the string and in some cases don´t.
NSString *Imagestuff= [[NSUserDefaults standardUserDefaults] objectForKey:#"DefaultcreateImageID"];
if ( [[NSUserDefaults standardUserDefaults] objectForKey:#"DefaultcreateImageID"] != ( NSString *) #"noImage" ){

iOS Core Data - Updating Multiple records

I've scoured and still haven't found anything that quite works. Either the question/answer is too old or it simply hasn't worked for me. This is my first attempt at "my own" app. As it seems a right of passage, I'm making a checklist app. Here's what I'm looking for:
My Data Store contains 4 attributes: name, category, isChecked, isActive (more will surely follow as I expand)
When my View Controller initially loads, the NSFetchedResultsController has an NSPredicate that only retrieves the records whose attribute isActive is YES (or [NSNumber numberWithBool:YES). It then takes those records and displays them into the appropriate cells for the user. When a user clicks on a cell, the Data Store updates and changes the isChecked attribute accordingly. Everything works good to this point.
What I need to do now is to be able to remove the items (1 or more) from the list. Specifically, I need it to update the Data Store attributes isChecked and isActive to NO only if it's current isChecked attribute is YES. (I'm not looking to delete the record from the data store as they will be used to build up the database for the users future use.)
I've used, among other things:
[[[self fetchedResultsController] fetchedObjects]
setValue:[NSNumber numberWithBool:NO]
forKey:#"isChecked"];
This does actually work, it removes the checkmark(s) and updates the store accordingly. Problem is, not only am I making another request to the data store for the isActive items, it also searches the entire "Active List" that was fetched and sets each of their isChecked attributes to NO. This may not be too big of an issue for small lists, but as the list(s) expand this can be an issue.
The other problem is, if I add:
[[[self fetchedResultsController] fetchedObjects]
setValue:[NSNumber numberWithBool:NO]
forKey:#"isActive"];
It sets ALL of my list items to NO (as well as a second data store request within the same method.)
So my question is: How can I get through the list, find only the items that are checked and update only those records (set both the isChecked && isActive attributes = NO) whose isChecked attribute is YES rather than working through the entire list?
I've tried creating a separate fetchedResultsController specifically for this buttons action, and it did work (that is to say, it didn't crash) but the debugger popped out a rather large 'Serious Application Error'. I won't post the error message as it's long and most likely irrelevant to any solution.
Any assistance would be greatly appreciated. Thanks in advance and please be gentle :-].
EDIT
I have tried using a for loop, for (NSString *item in fetchedResultsController) but I get the error ...may not respond to 'countByEnumeratingWithState:objects:count'
It seems a loop of sorts is what's needed here, but again, nothing I can find is relevant or it's outdated. Again, thanks for any assistance.
Edit 2
Here is the original error I got when I ran a second separate fetchRequestController for this button/method:
An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. 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 (0 inserted, 3 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out). with userInfo (null)
You can just loop over the fetchedObjects collection and change the managed objects. After changing them you'll need to reload your list (I guess you use a tableview).
I don't know what your classes are named, but in general you can just loop over the collection of managed objects and change them. Remember that you need to save your managed object context if you want to keep these changes for when the app closes.
NSArray* myCollection = [[self fetchedResultsController] fetchedObjects];
for(ActiveListData *managedObject in myCollection)
{
if(managedObject != nil && managedObject.isChecked)
{
managedObject.isChecked = NO;
managedObject.isActive = NO;
}
}
If you want to do the check on all object in the database you'll need a new method in your NSFetchedResultsController that has a predicate checking on isChecked and then loops over and edits the result collection.
You might want to post your error code as we could be able to point out what you did wrong.
Edit: If you're not familiar with using Core Data the apple documentation provides a lot of information: http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/Articles/cdBasics.html
Thanks to #ggfela for his answer. The processes of his answer were spot on. Here is the actual code I put into my button/method, in hopes of it helping someone else in the future:
NSArray *moc = [[self fetchedResultsController] fetchedObjects];
for (ActiveListData *item in moc) {
if (item != nil && item.isChecked.boolValue == 1) {
item.isChecked = [NSNumber numberWithBool:NO];
item.isActive = [NSNumber numberWithBool:NO];
}
}
// Call to Data Store to update the list
NSError *error;
if (![self.managedObjectContext save:&error]) {
FATAL_CORE_DATA_ERROR(error);
return;
Explanation:
Load the contents of the result from calling the fetchedResultsController method into a temporary variable named moc
Use a for loop to cycle through the array of moc. ActiveListData is the NSManagedObject subclass that I created for my Core Data and is the proper place to insert the separated values/attributes from the data store. From there, it's pretty simple, I ensure that item is not nil AND that the item's attribute is the value I need.
NOTE
Core Data does not store the bool values YES and NO but rather 1 and 0, respectively but when you call or compare the values, you simply can not compare the value of item.isChecked because it is being passed back to you as a bool not as an integer. You can not simply compare item.isChecked == YES either since the #property of isChecked is an NSNumber. So, in the case of the if I put item.isChecked.boolValue as this will give me the representing integer for it's bool value, in this case I have it check for a 1 (YES). (Sorry if my explanation is wrong and/or confusing, but this is how I understand it and is the only way this code works.)
Then, setting the new values of these attributes is like you would expect when setting any other variable. The only "tricky" difference with this is that the NSManagedObject subclass sets the #property of the isChecked and isActive to an NSNumber (as mentioned earlier) so in order to send the proper values back to Core Data you use the method numberWithBool of the NSNumber class.
And just in case anyone gets confused by my FATAL_CORE_DATA_ERROR(error) call this is simply a macro that was defined inside the Prefix.pch file to handle my errors from the managedObjectContext. You can use any (or none) error handling you choose.
Thanks again #ggfela for your help!! If anyone else has any other suggestions on how this code should be applied, then please let me know!
You can use NSBatchUpdateRequest to update multiple records
Examples:
https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
http://code.tutsplus.com/tutorials/ios-8-core-data-and-batch-updates--cms-22164

Object is deallocated - why? where?

Ok, I spent the last 8 hours fighting with it - it just seems beyond me. Here's my complete (relevant) code:
- (void)updateUserDefaults
{
NSMutableDictionary *viewControllerDetails = [[NSMutableDictionary alloc] initWithCapacity:4];
[viewControllerDetails setObject:[NSNumber numberWithInt:OOVenueClassControllerType] forKey:#"classType"];
[viewControllerDetails setObject:self.searchTerm forKey:#"searchTerm"];
[viewControllerDetails setObject:self.searchLocation forKey:#"searchLocation"];
//----- the next two lines cause the problem
NSString *res = [[NSString stringWithFormat:#"%#",[searchResults xmlString]] retain];
[viewControllerDetails setObject:res forKey:#"searchresults"];
//-----
NSMutableArray *viewControllersList = [NSMutableArray array] ;
[viewControllersList addObject:viewControllerDetails];
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
//the following line causes the error
[defs setObject:viewControllersList forKey:kViewControllersKey];
[defs synchronize];
[res release];
}
Note the block with the next two lines cause the problem. At first I didn't create another string, but added it later while trying to solve the problem.
If I comment out those two lines, everything works fine. If I put them back in, I get
- [CFString class]: message sent to deallocated instance 0xa1a9000
Is something is wrong with the string that I'm trying to put into the userdefaults? That string is rather large (about 200,000 characters), but I had stored even longer strings in user defaults in the past.
It's also worth noting that if I uninstall the app, then everything works fine. But on subsequent runs the problem exhibits itself.
So, how and why and where is the string getting deallocated? I have explicitly added retain - but that still doesn't help. What am I missing?
Edit: just realised I forgot to say that the error is thrown on line
[defs setObject:viewControllersList forKey:kViewControllersKey];
Also, for general information, method - (NSString *)xmlString on searchResults does exactly what the name means: creates an XML string with the information from that object.
Edit 2: I tried doing something else with that string - convert it to NSData, compress using zlib - but regardless of data type, that particular object gets deallocated. Does it have to do something with the size of the string?
NSString *res = [[NSString stringWithFormat:#"%#",[searchResults xmlString]] retain];
Is auto released. You don't need to release it at the end of your method. You are over-releasing it.
Further, you don't need to retain the [searchResults xmlString]. The stringWithFormat method already does it for you.
Good Luck!
Ok, not sure what exactly the problem was, but it was somewhere in the searchResults and/or xmlString method. searchResults object is originally created from XML received from the server (XML is parsed into the object structure). When xmlString was called, for some reason the string I was getting back was different from the original XML (I'm not talking about formatting, of course) - of 200,000 char-long string, within the first 500 chars or so there were some differences. I haven't been able to figure out why. So, instead of recreating the xml from object structure, I instead stored the original XML in a field in that object and, when xmlString was called, simply returned the original string. Now everything worked fine.
Thank you all for your support through this painful process.

Core Data: Adding objects from NSMutableArray to NSMutableSet?

Judging from the amount of related questions that were brought up, this looks like a frequently asked question which makes me all the more hesitant to ask it. I have looked at a majority of these questions but none of them seem to address the specific problem I am having trouble figuring out.
A little background information on what I'm trying to achieve, how I am going about it, and what issue I am having:
I am trying to parse an XML web service, load that data into an NSMutableArray(Or any other place from which I can access it later), and then take my data and load it into my Core Data model. The first part of this I can do, its once I have my information in the array and trying to load it into Core Data that I cannot seem to progress.
My model(simplified for this question) consists of a route entity that has a one to many relationship with a checkpoint entity. The data I would be trying to load is a variety of attribute information into my route entity, which is not included in my array, and then my list of checkpoints, which is what the array is. My problem is that I cannot reliably add my entire array of checkpoints and then save. For the static case I am using for development, I have a consistent 20 checkpoints being parsed into my NSMutableArray, of these, the most I have been able to transfer into my NSMutableSet aka the checkpoints part of my route entity is 7 before crashing with either a SIGABRT, or EXC_BAD ACCESS, or incorrect selector sent. I have been trying to figure it out for the better part of today with no luck. Now for some code:
NSManagedObjectContext *context = [appDelegate managedObjectContext];
//newRoute is the route that I am trying to create and then store persistently
newRoute = [NSEntityDescription insertNewObjectForEntityForName:#"Route" inManagedObjectContext:context];
//filling in some available attribute information
if (name.text == #"")
[newRoute setValue:[NSDate date] forKey:#"name"];
else
[newRoute setValue:name.text forKey:#"name"];
NSMutableSet *muteSet = [newRoute mutableSetValueForKey:#"myCheckpoints"];
for (int i = 0; i < [appDelegate.checkpoints count]; i++ )
{
Checkpoint *newCheckpoint = [[Checkpoint alloc] init];
[newCheckpoint setName:[[appDelegate.checkpoints objectAtIndex:i] valueForKey:#"name"]];
NSLog(#"Appending %# to set", newCheckpoint.name);
[muteSet addObject:newCheckpoint];
[newCheckpoint release];
}
//myCheckpoints is the route<-->>checkpoints relationship
[newRoute setValue:muteSet forKey:#"myCheckpoints"];
// Save the context.
NSError *error = nil;
if (![context save:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
Out of curiosity, why doesn't the following work?
NSSet *ckPtSet = [[NSSet alloc] initWithArray:appDelegate.checkpoints];
[newRoute setValue:ckPtSet forKey:#"myCheckpoints"];
As far as I understand, and this might be where the problem is... when setting the value of myCheckpoints, the expectation is to be passed an NSSet. When going through with the debugger the initialized set actually contains the 20 objects, but when I try to step past I get the incorrect selector received error again.
Anyways, thank you for taking the time to read my wall of text, if you need more to help please let me know and I will add it asap!
-Karoly
The documentation for [id<NSKeyValueCoding> mutableSetValueForKey:] states that it returns a mutable set proxy that provides read-write access to the unordered to-many relationship specified by a given key. This means that the object returned isn't necessarily an NSMutableSet instance per se, but a proxy wherein any changes you make to that object are reflected in your model's set itself.
This might be why [newRoute setValue:muteSet forKey:#"myCheckpoints"]; is giving you troubles. I find that a better way to think about it is to not have an intermediate object, but to nest calls, e.g.:
[[newRoute mutableSetValueForKey:#"myCheckpoints"] addObject:newCheckpoint];

EXC_MEMORY_ACCESS when trying to delete from Core Data ($cash solution)

I have an application that downloads an xml file, parses the file, and creates core data objects while doing so. In the parse code I have a function called 'emptydatacontext' that removes all items from Core Data before creating replacements items from the xml data. This method looks like this:
-(void) emptyDataContext
{
NSFetchRequest * allCon = [[NSFetchRequest alloc] init];
[allCon setEntity:[NSEntityDescription entityForName:#"Condition" inManagedObjectContext:managedObjectContext]];
NSError * error = nil;
NSArray * conditions = [managedObjectContext executeFetchRequest:allCon error:&error];
DebugLog(#"ERROR: %#",error);
DebugLog(#"RETRIEVED: %#", conditions);
[allCon release];
for (NSManagedObject * condition in conditions) {
[managedObjectContext deleteObject:condition];
}
// Update the data model effectivly removing the objects we removed above.
//NSError *error;
if (![managedObjectContext save:&error]) {
DebugLog(#"%#", [error domain]);
}
}
The first time this runs it deletes all objects and functions as it should - creating new objects from the xml file. I created a 'update' button that starts the exact same process of retrieving the file the proceeding with the parse & build. All is well until its time to delete the core data objects. This 'deleteObject' call creates a "EXC_BAD_ACCESS" error each time. This only happens on the second time through.
Captured errors return null. If I log the 'conditions' array I get a list of NSManagedObjects on the first run. On the second this log request causes a crash exactly as the deleteObject call does.
I have a feeling it is something very simple I'm missing or not doing correctly to cause this behavior. The data works great on my tableviews - its only when trying to update I get the crashes.
I have spent days & days on this trying numerous alternative methods. Whats left of my hair is falling out. I'd be willing to ante up some cash for anyone willing to look at my code and see what I'm doing wrong. Just need to get past this hurdle.
Thanks in advance for the help!
Did you save the context after removing the objects in the for loop? Be aware that deleteObject: does not delete the object immediately, it simply schedule it for deletion when changes are committed, i.e., when you save the context.
EDIT: Your problem may be related to how you present your data to the user on your table view. Without additional code is difficult to tell exactly (are you using NSFetchedResultsController or not?), but my guess is that the interaction between deleting the data and showing them on the table is not correct. Probably, what is happening is that your table is told to visualize your data, but then, when you delete them, you are not updating correctly the table.
Wow, so after a few days of testing I went down a path that led me to tracking down Zombies & memory mgmt. This was a situation where the errors I was recieving were leftover from issues in another area. When parsing the data and placing it into Core Data I released an object that was to be autoreleased. So any subsequent calls to that item within core data (save, deletec, etc) caused a crash. Thank you all for your help and I vow to pay closer attention with my memory mgmt calls.