NSArray from NSSet of objects crashes when calling 'allObjects' - iphone

I have an core data NSSet of objects through a relationship that I am trying to put into an array.
When I call the 'allObjects' selector I get a crash on my object in the NSSet that the selector does not exist. Well, it obviously doesn't, but how do I get my data to copy into the array?
Heres the code that crashes.
NSArray *items = [surveyCategory.surveyQuestions allObjects];
Inside my surveyQuestions NSSet are SurveyQuestion objects. And this throws the error `[SurveyQuestion allObjects]: unrecognized selector sent to instance
Any ideas on how to fix this?
thanks

From the error message it looks as if surveyQuestions is not a to-many relationship
as you expect, but a to-one relationship, so that surveyCategory.surveyQuestions
is a SurveyQuestion object and not a set.
Perhaps you changed the Core Data model and did not re-create the managed object subclass
file, so that the compiler did not complain.

Related

coredata how to change default NSSet to NSMutableArray

CoreData one-to-many default to generate NSSet ,how to change NSSet to NSMutableArray?I try to change it manually,but get error:
_NSFaultingMutableSet filteredArrayUsingPredicate:]: unrecognized selector sent to instance 0x1ed35e40'
NSSet has the method allObjects, which returns an NSArray.
To get an NSMutableArray you could do this:
NSMutableArray *array = [NSMutableArray arrayWithArray:myCoreDataObject.mySet.allObjects];
Note: order is not guaranteed to be the same every time (sets aren't ordered). If order is important to you, consider an NSOrderedSet instead.
See also the docs on NSSet:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSSet_Class/Reference/Reference.html
PS:
The reason you're getting said error:
NSSet (or _NSFaultingMutableSet for that matter) doesn't have a method called filteredArrayUsingPredicate.

JSON to core-data

I am trying to save JSON response to local core-data for my app. I am following the following implementation for this:
https://stackoverflow.com/a/2363996/127036
Here is my code:
NSString *objectName = #"Post";
NSManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:objectName inManagedObjectContext:moc];
[managedObject setValuesForKeysWithDictionary:structureDictionary];
Compiler returns following error:
-[__NSCFDictionary entity]: unrecognized selector sent to instance 0x6dc6fa0
While trying to execute:
setValuesForKeysWithDictionary
Please guide me in the right direction to fix this issue.
I'm not seeing setValuesForKeysWithDictionary in the dev center for NSManagedObject
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObject_Class/Reference/NSManagedObject.html
You may have to loop through and do them one at a time with setValue:forKey:
This post is quite old now and I'm sure the Vibhor Goyal has already moved on. But in case anyone runs into this same problem, the reason why he's getting
-[__NSCFDictionary entity]: unrecognized selector sent to instance
Is because in his Post model, I'm sure he has sub entities, probably something like "comments" which is probably a to-many relationship to a "Comment" model.
Then in his structureDictionary, he probably has the usual key-value fields that corresponds to his Post model, and for the "comments" key he probably has a NSSet of NSDictionaries for the value.
So the reason why he's getting that entity selector error is because under the hood, core data is expecting "comments" to be a set filled with instances of "Comment" which are supposed to be instances of NSManagedObject, but instead it's getting instances of NSDictionary. So when it asks for "entity" from each of the "comments" it throws the unrecognized selector error.
Hope this helps someone in the future.

iPhone Core Data - cannot fulfill a fault error

I have three classes, A, B and C. A is the main class.
When the user wants to see the list of all objects that were purchased, Class B is called from A and shows the list of objects in a core data entity.
Inside class B, the user can buy new objects (in-app purchase). When the user wants to buy another object, class C is called.
When class C is called, a new object is created on the core data entity using
anObject = [NSEntityDescription insertNewObjectForEntityForName:#"Objects" inManagedObjectContext:context];
this object is then assigned to a local reference on Class C, using something like
self.object = anObject;
this object variable was declared like this:
.h
MyObjects *object;
#property (nonatomic, retain) MyObjects *object;
and #synthesized on .m
MyObjects is a core data class representing the entity.
In theory, object will retain anything assigned to it, so the line self.object = anObject I typed previously will retain anObject reference on self.object, right?
The problem is that when I try to access self.object in the same class after buying the new object, I receive an error "CoreData could not fulfill a fault for XXX", where XXX is exactly self.object.
At no point in the code there's any object removal from the database. The only operation to the database I could identify was a saving operation done by another class moments before the crash. The save is done by something like
if (![self.managedObjectContext save:&error]) ...
Is there any relation? what may be causing that?
CoreData manages the lifetime of managed objects and you should not retain and release them. If you want to keep a reference to the object so that it can be retrieved later then you have to store the object's id (obtained using -[NSManagedObject objectID]). Then use that to retrieve the object later using -[NSManagedObjectContext objectWithID:].
Make sure you understand about CoreData faulting. Read the documentation.
I had a similar issue a few days ago (using NSFetchedResultsController) where I was placing my fetchedObjects into an array and gathering attributes to populate tables from the array objects. It seems that if the objects in the array are faulted, you cannot unfault it unless you are acting on the direct object. In my case, I solved the issue by taking the lines of code in question and calling [[_fetchedResultsController objectAtIndexPath:indexPath] someAttribute]. I would assume that doing something similar would fix your problem as well. It seems a bit tedious to need to fetch from the managedObjectContext to obtain a faulted value, but this was the only way I could personally get past the issue.
Core Data is responsible for managing the lifetime of managed objects in memory. It's really important to understand Managed Object Contexts - Read the documentation.
Apple also provides an entire troubleshooting section here, and it contains among other things the causes for your error. But it's really only useful if you understand how core data works.
Most likely error is that the object you are saving does not belong to the managed object context.
Say you use the same object on different threads and those different threads use different managed object context, then this will happen.

Application crash problem in iPhone

I have used NSMutable Dictionary and NSMutable Array. The datas are to be stored and retrieved from plist(Documents Directory) using NSArray of NSMutable Dictionary.
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object'
Please Guide me why its happened?.
Thanks!
It might help if you post the exact code that causes. My guess would be that while you are using NSMutableDictionary, the call to valueForKey: returns to you a non-mutable NSArray, and you think it is returning you an NSMutableArray instance. Note that mutable arrays and dictionaries allow you to manipulate the collection of items inside them, but do not guarantee you that those items themselves are mutable. For example, if you check the Property List Programming Guide: Reading and Writing Property-List Data, you will notice the following example:
If you load the property list with
this call:
NSMutableArray * ma = [NSMutableArray arrayWithContentsOfFile:xmlFile];
ma is a mutable array with immutable
dictionaries in each element. Each key
and each value in each dictionary are
immutable.
If you need explicit control over the mutability of the objects at each level, use propertyListFromData:mutabilityOption:format:errorDescription:
You can also create an explicit NSMutableArray copy from the NSArray you got from the NSMutableDictionary.
you said you are retrieving the array as a NSArray and not casting it to a NSMutableArray before you attempt to remove an object for it. This causes an error since you can't remove an object from an NSArray
Suppose [something dictionaryValue] returns an immutable dictionary, and you want a mutable version of that dictionary. It is not enough to say:
NSMutableDictionary *d = [something dictionaryValue];
This merely tells the compiler that d is an NSMutableDictionary, but really it's the same immutable dictionary you got from [something dictionaryValue]. Instead, you need to create a new, mutable copy of the dictionary:
NSMutableDictionary *d = [NSMutableDictionary dictionaryWithDictionary:
[something dictionaryValue]];
Similarly, use [NSMutableArray arrayWithArray:...] for arrays.

insertNewObjectForEntityForName:inManagedObjectContext: returning NSNumber bug?

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?
I had the very same issue: I had added a method called "isDatabase" (returning a BOOL) to the parent entity of my Database entity, which had a relationship named "database". Renaming "isDatabase" to "isOfTypeDatabase" fixed the issue. So keep also looking in parent entities!
I defined a property on an NSManagedObject subclass that collided with the name of a relationship defined on the class.
Here's the code in my MyManagedObjectSubclass+Custom.h
#property (readonly, nonatomic) BOOL isSeason;
Here's the code produced by XCode for MyManagedObjectSubclass.h
#property (nonatomic, retain) SomeOtherEntityToOneRelationship *season;
Note that isSeason, by KVC, will collide with the season name
I ran into the exact same problem and after pulling my hair out for an entire day, I solved my problem.
I believe the problem is related to a corrupt attribute / relationship, and the NSCFNumber is actually looking for the objectID for that attribute / relationship. In my case, I could use valueForKey: to find all of the attributes / relationships, although a relationship I had called "file" seemed to be corrupt.
I finally realized that I had extended NSObject to include a boolean "isFile" method, and somehow this was interfering with CoreData and causing it to either return a corrupt object, or not be able to deal properly with the object it had. My guess is that CoreData must dynamically create "isXXX" methods.
I could either fix the problem by removing the isFile method, or by renaming my property.
The objectID and entity selectors are on NSManagedObject, not NSCFNumber (or NSNumber). I wouldn't expect you to call either of these selectors on a NSNumber which should be a property on an entity, not the entity itself.
Every entity in CoreData must extend NSManagedObject, so your NSCFNumber object is not an entity.