Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MagicalRecord not returning NSDictionary in fetch request

Here is my code:

NSPredicate *filter = [NSPredicate predicateWithFormat:@"aMostRecentFlag == 1"];  //  find old records
NSFetchRequest *fetchRequest = [PreferenceData MR_requestAllWithPredicate: filter];
[fetchRequest setResultType: NSDictionaryResultType];

NSDictionary *preferenceData = [PreferenceData MR_executeFetchRequest:fetchRequest];

I get a warning from the build:

Incompatible pointer types initializing 'NSDictionary *' with an expression of type 'NSArray *'

which indicates MR is not returning the NSDictionary as documented; is there something wrong with my code? And by the way, nothing is returned by the fetch request, although there is a record that should have been.

like image 829
SpokaneDude Avatar asked Oct 26 '15 20:10

SpokaneDude


1 Answers

It seems the comments have worked out the answer, but I am not sure that everyone is clear.

A fetch request returns an array of results. Usually, the objects representing the results will be the class specified in the model. If you are subclassing NSManagedObject (as you should be), it will be the subclass. If not, it will be a generic-looking NSManagedObject whose properties you access through valueForKey:.

However, you can ask for the results to be returned as dictionaries. This doesn't mean that executeFetchRequest:error: method returns a dictionary. Rather, it means that each object in the array will be a dictionary.

Whichever format you get the results in, you have to pull the object(s) you care about out of the array. A common idiom is to simply append .lastObject or .firstObject to the end of the executeFetchRequest:error: invocation. Something like:

MyObject *object = [context executeFetchRequest:request error:NULL].firstObject;

Magical Record is nothing more than a fancy wrapper around Core Data classes. It provides convenience methods, but all the usual semantics of Core Data still hold.

like image 134
Avi Avatar answered Nov 01 '22 20:11

Avi