Search code examples
core-dataxcode7magicalrecord-2.2

How to get fields (attributes) out of a single CoreData record without using [index]?


I have one CoreData record that contains all of the app's settings. When I read that single record (using MagicalRecord), I get an array back. My question is: can I get addressabiltiy to the individual fields in the record without using "[0]" (field index), but rather using [@"shopOpens"]?

I was thinking something like this, but I don't think it's right:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"aMostRecentFlag == 1"];  //  find old records
preferenceData = [PreferenceData MR_findAllWithPredicate:predicate inContext:defaultContext];  //  source

   NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *preferencesDict = [[userDefaults dictionaryForKey:@"preferencesDictionary"] mutableCopy];  //  target

//  start filling the userDefaults from the last Preferences record
/*
 Printing description of preferencesDict: {
 apptInterval = 15;
 colorScheme = Saori;
 servicesType = 1;
 shopCloses = 2000;
 shopOpens = 900;
 showServices = 0;
 syncToiCloud = 0;
 timeFormat = 12;
 }
 */

[preferencesDict setObject: preferenceData.colorScheme  forKey:@"shopOpens"];

UPDATE

This is how I finally figured it out, for those who have a similar question:

NSPredicate *filter = [NSPredicate predicateWithFormat:@"aMostRecentFlag == 0"];  //  find old records
NSFetchRequest *freqest = [PreferenceData MR_requestAllWithPredicate: filter];
[freqest setResultType: NSDictionaryResultType];
NSDictionary *perferenceData = [PreferenceData MR_executeFetchRequest:freqest];

Solution

  • Disclaimer: I've never used magical record, so the very first part is just an educated guess.

    I imagine that preferenceData is an instance of NSArray firstly because the method name uses findAll which indicates that it will return multiple instances. Secondly, a normal core data fetch returns an array, and there is no obvious reason for that find method to return anything different. Thirdly, you referenced using an index operation in your question.

    So, preferenceData is most likely an array of all objects in the store that match the specified predicate. You indicated that there is only one such object, which means you can just grab the first one.

    PreferenceData *preferenceData = [[PreferenceData
        MR_findAllWithPredicate:predicate inContext:defaultContext] firstObject];
    

    Now, unless it is nil, you have the object from the core data store.

    You should be able to reference it in any way you like to access its attributes.

    Note, however, that you can fetch objects from core data as dictionary using NSDictionaryResultType, which may be a better alternative for you.

    Also, you can send dictionaryWithValuesForKeys: to a managed object to get a dictionary of specific attributes.