Skip to content


Subversion checkout URL

You can clone with
Download ZIP


Importing Data #532

emadd opened this Issue · 40 comments

5 participants


I'm getting a strange error (EXC_BAD_ACCESS by CFStringGetLength within NSManagedObject(MagicalRecord)MR_executeFetchRequest:inContext:) I can't make sense of when attempting to import data from a JSON file...

NSManagedObjectContext *opContext = [NSManagedObjectContext MR_contextForCurrentThread];

    NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"DefaultData"
    NSData *data = [NSData dataWithContentsOfFile:jsonPath];

    NSError *parseError;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&parseError];

    NSArray *dataTypes = [json objectForKey:@"dataTypes"];

    [MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
        for (NSDictionary *obj in dataTypes) {
            DLog(@"%@", obj);
            [BTDataType MR_importFromObject:obj inContext:localContext];

    NSError *saveError;
    [opContext save:&saveError];

The entity is very simple, just two properties: importKey (int16) and name (String)...

The JSON is like...

"name":"DataType A"
"name":"DataType B"
"name":"DataType C"
"name":"DataType D"


I'm having this same issue. I have tried both 2.1 and 2.2 on both iOS 6 and iOS 7. Anyway to get around it? I have tried both importFromArray and importFromObject.


Looking at the fork logs, it seems a fix may be in the repo, instead of obtaining a release just checkout the root for develop. I will test this to confirm.


nvm, still having the issue. My code is.

ApiClient *client = [ApiClient sharedInstance];

    NSDictionary *dataDictionary = [[NSDictionary alloc] initWithObjects:@[searchString] forKeys:@[@"companyName"]];
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dataDictionary options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    NSString *token = [[[UserManager sharedInstance] getAuthenticationObject] authenticationToken];

    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjects:@[@"json", token, jsonString ]
                                                                       forKeys:@[@"callType", @"token", @"data"]];

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [client getPath:@"GetClientInterfaces/" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        NSLog(@"Operation: %@", operation);
        NSLog(@"Response: %@", responseObject);
        NSLog(@"Type: %@", [[responseObject valueForKeyPath:@"details.items"] class]);
        NSLog(@"First: %@", [[responseObject valueForKeyPath:@"details.items"] firstObject]);
        NSArray *providerResults = [responseObject valueForKeyPath:@"details.items"];
        NSLog(@"Results: %@", providerResults);
        __block NSArray *array;
        [MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
            array = [ProviderSearchResults MR_importFromArray:providerResults];
            NSLog(@"Array1: %@", array);
        NSLog(@"Array: %@", array);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        NSLog(@"Operation: %@", operation);
        NSLog(@"Error: %@", error);

I have even tried doing a for loop and adding them as objects.


@casademora I looked at that page and followed it yet I am still having the issue.


@casademora I don't have mapping since my core data matches my keys. Per your article it said if your data matches then read no further.

    details =     {
        items =         (
                address1 = "";
                clientId = 1;
                companyName = "Test";
                id = 123;
                nameLink = test;
                address1 = "123 St.";
                clientId = 2;
                companyName = "Test 2";
                id = 124;
                nameLink = test2;


@interface ProviderSearchResults : NSManagedObject

@property (nonatomic, retain) NSNumber * id;
@property (nonatomic, retain) NSString * companyName;
@property (nonatomic, retain) NSString * nameLink;
@property (nonatomic, retain) NSString * address1;
@property (nonatomic, retain) NSNumber * clientId;


I know it isn't good practice but I have used id before when it refers to core data. Also yes, the entity has these as I generated the managed object class from the entity via Xcode CreateManagedObjectClass Generator.


This is the crash log from Crashlytics. It is just an assembly error through Xcode.

0NSManagedObjectContext Queue Crashed
0    CoreFoundation      CFStringGetLength + 18
1    CoreFoundation  CFStringFind + 18
2    CoreData    -[NSFunctionExpression(_NSCoreDataSQLPredicateCategories) _mapKVCOperatorsToFunctionsInContext:] + 158
3    CoreData    -[NSFunctionExpression(_NSCoreDataSQLPredicateCategories) minimalFormInContext:] + 684
4    CoreData    -[NSComparisonPredicate(_NSCoreDataSQLPredicateCategories) minimalFormInContext:] + 64
5    CoreData    -[NSSQLGenerator predicateForFetchRequestInContext:] + 781
6    CoreData    -[NSSQLGenerator initializeContextForFetchRequest:ignoreInheritance:nestingLevel:] + 603
7    CoreData    -[NSSQLGenerator newSQLStatementForFetchRequest:ignoreInheritance:countOnly:nestingLevel:] + 58
8    CoreData    -[NSSQLAdapter _newSelectStatementWithFetchRequest:ignoreInheritance:] + 472
9    CoreData    -[NSSQLAdapter newSelectStatementWithFetchRequest:] + 48
10   CoreData    -[NSSQLCore newRowsForFetchPlan:] + 129
11   CoreData    -[NSSQLCore objectsForFetchRequest:inContext:] + 701
12   CoreData    -[NSSQLCore executeRequest:withContext:error:] + 383
13   CoreData    -[NSPersistentStoreCoordinator executeRequest:withContext:error:] + 4466
14   CoreData    -[NSManagedObjectContext executeFetchRequest:error:] + 566
15   CoreData    -[NSManagedObjectContext(_NestedContextSupport) _parentObjectsForFetchRequest:inContext:error:] + 502
16   CoreData    __82-[NSManagedObjectContext(_NestedContextSupport) executeRequest:withContext:error:]_block_invoke + 676
17   CoreData    internalBlockToNSManagedObjectContextPerform + 17
18 ...   libdispatch.dylib   _dispatch_client_callout + 14
20   libdispatch.dylib   dispatch_barrier_sync_f + 87
21   CoreData    _perform + 114
22   CoreData    -[NSManagedObjectContext(_NestedContextSupport) executeRequest:withContext:error:] + 238
23   CoreData    -[NSManagedObjectContext executeFetchRequest:error:] + 566
24   CoreData    -[NSManagedObjectContext(_NestedContextSupport) _parentObjectsForFetchRequest:inContext:error:] + 502
25   CoreData    __82-[NSManagedObjectContext(_NestedContextSupport) executeRequest:withContext:error:]_block_invoke + 676
26   CoreData    internalBlockToNSManagedObjectContextPerform + 17
27 ...   libdispatch.dylib   _dispatch_barrier_sync_f_slow_invoke + 71
36   UIKit   UIApplicationMain + 1225
37   Customer View  
main.m line 16
38   libdyld.dylib   start

In Xcode the debug on the left shows

#0  0x01d3d222 in CFStringGetLength ()
#1  0x01d53302 in CFStringFind ()
#2  0x013ce4ee in -[NSFunctionExpression(_NSCoreDataSQLPredicateCategories) _mapKVCOperatorsToFunctionsInContext:] ()
#3  0x013ce22c in -[NSFunctionExpression(_NSCoreDataSQLPredicateCategories) minimalFormInContext:] ()
#4  0x013cdb90 in -[NSComparisonPredicate(_NSCoreDataSQLPredicateCategories) minimalFormInContext:] ()
#5  0x013cd2cd in -[NSSQLGenerator predicateForFetchRequestInContext:] ()
#6  0x013ccb8b in -[NSSQLGenerator initializeContextForFetchRequest:ignoreInheritance:nestingLevel:] ()
#7  0x013cc44a in -[NSSQLGenerator newSQLStatementForFetchRequest:ignoreInheritance:countOnly:nestingLevel:] ()
#8  0x013cc2b8 in -[NSSQLAdapter _newSelectStatementWithFetchRequest:ignoreInheritance:] ()
#9  0x013cc0d0 in -[NSSQLAdapter newSelectStatementWithFetchRequest:] ()
#10 0x013cbe91 in -[NSSQLCore newRowsForFetchPlan:] ()
#11 0x013cb61d in -[NSSQLCore objectsForFetchRequest:inContext:] ()
#12 0x013cb0cf in -[NSSQLCore executeRequest:withContext:error:] ()
#13 0x013caaf2 in -[NSPersistentStoreCoordinator executeRequest:withContext:error:] ()
#14 0x013c8256 in -[NSManagedObjectContext executeFetchRequest:error:] ()
#15 0x0141cdc6 in -[NSManagedObjectContext(_NestedContextSupport) _parentObjectsForFetchRequest:inContext:error:] ()
#16 0x0149a814 in __82-[NSManagedObjectContext(_NestedContextSupport) executeRequest:withContext:error:]_block_invoke ()
#17 0x0141cbc1 in internalBlockToNSManagedObjectContextPerform ()
#18 0x021674b0 in _dispatch_client_callout ()
#19 0x021547e5 in _dispatch_barrier_sync_f_invoke ()
#20 0x02154423 in dispatch_barrier_sync_f ()
#21 0x0141cb42 in _perform ()
#22 0x0141c9ee in -[NSManagedObjectContext(_NestedContextSupport) executeRequest:withContext:error:] ()
#23 0x013c8256 in -[NSManagedObjectContext executeFetchRequest:error:] ()
#24 0x000084f0 in __67+[NSManagedObject(MagicalRecord) MR_executeFetchRequest:inContext:]_block_invoke at /Customer View/MagicalRecord/Categories/NSManagedObject/NSManagedObject+MagicalRecord.m:33
#25 0x0141c88f in developerSubmittedBlockToNSManagedObjectContextPerform ()
#26 0x0141c7cc in -[NSManagedObjectContext performBlockAndWait:] ()
#27 0x000082c1 in +[NSManagedObject(MagicalRecord) MR_executeFetchRequest:inContext:] at /Customer View/MagicalRecord/Categories/NSManagedObject/NSManagedObject+MagicalRecord.m:29
#28 0x00008834 in +[NSManagedObject(MagicalRecord) MR_executeFetchRequestAndReturnFirstObject:inContext:] at /Customer View/MagicalRecord/Categories/NSManagedObject/NSManagedObject+MagicalRecord.m:53
#29 0x00013bd3 in +[NSManagedObject(MagicalFinders) MR_findFirstByAttribute:withValue:inContext:] at /Customer View/MagicalRecord/Categories/NSManagedObject/NSManagedObject+MagicalFinders.m:94
#30 0x0001ef83 in +[NSManagedObject(MagicalRecord_DataImport) MR_importFromObject:inContext:] at /Customer View/MagicalRecord/Categories/NSManagedObject/NSManagedObject+MagicalDataImport.m:251
#31 0x0001f4b9 in __74+[NSManagedObject(MagicalRecord_DataImport) MR_importFromArray:inContext:]_block_invoke at /Customer View/MagicalRecord/Categories/NSManagedObject/NSManagedObject+MagicalDataImport.m:280
#32 0x01db6edb in __NSArrayEnumerate ()
#33 0x01db6a86 in -[NSArray enumerateObjectsWithOptions:usingBlock:] ()
#34 0x01db6995 in -[NSArray enumerateObjectsUsingBlock:] ()
#35 0x0001f375 in +[NSManagedObject(MagicalRecord_DataImport) MR_importFromArray:inContext:] at /Customer View/MagicalRecord/Categories/NSManagedObject/NSManagedObject+MagicalDataImport.m:276
#36 0x0001f21b in +[NSManagedObject(MagicalRecord_DataImport) MR_importFromArray:] at /Customer View/MagicalRecord/Categories/NSManagedObject/NSManagedObject+MagicalDataImport.m:269
#37 0x0000c1de in __52+[ProviderSearch searchForProvidersByName:forTable:]_block_invoke55 at /Customer View/ProviderSearch.m:41
#38 0x00019c62 in __47+[MagicalRecord(Actions) saveWithBlockAndWait:]_block_invoke at /Customer View/MagicalRecord/Core/MagicalRecord+Actions.m:58
#39 0x0141c88f in developerSubmittedBlockToNSManagedObjectContextPerform ()
#40 0x021674b0 in _dispatch_client_callout ()
#41 0x021547e5 in _dispatch_barrier_sync_f_invoke ()
#42 0x02154423 in dispatch_barrier_sync_f ()
#43 0x0141c7bf in -[NSManagedObjectContext performBlockAndWait:] ()
#44 0x00019b92 in +[MagicalRecord(Actions) saveWithBlockAndWait:] at /Customer View/MagicalRecord/Core/MagicalRecord+Actions.m:56
#45 0x0000bfb7 in __52+[ProviderSearch searchForProvidersByName:forTable:]_block_invoke at /Customer View/ProviderSearch.m:40
#46 0x00091acb in __64-[AFJSONRequestOperation setCompletionBlockWithSuccess:failure:]_block_invoke91 at /Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.m:140
#47 0x02152828 in _dispatch_call_block_and_release ()
#48 0x021674b0 in _dispatch_client_callout ()
#49 0x02155752 in _dispatch_main_queue_callback_4CF ()
#51 0x01d62ffb in __CFRunLoopRun ()
#52 0x01d62403 in CFRunLoopRunSpecific ()
#53 0x01d6221b in CFRunLoopRunInMode ()
#54 0x039cda37 in GSEventRunModal ()
#55 0x039cd85e in GSEventRun ()
#56 0x0056b6bb in UIApplicationMain ()
#57 0x0002dd9d in main at /Customer View/main.m:16


@casademora I had inContext:localContext before then took it out to see if that would work. It seems to be crashing at the results = [context executeFetchRequest:request error:&error]; in + (NSArray *) MR_executeFetchRequest:(NSFetchRequest *)request inContext:(NSManagedObjectContext *)context. There is no errormessage, just (lldb) at the bottom. The only error indicator I get is EXC_BAD_ACCESS


@casademora is it possible to only do a mapping for id and let MR do the auto mapping for the rest since they match? I could map id to masterId


I changed id to come back as something different and still having the crash so we can rule that out.


@casademora I'm at a loss. I set exception logging and nothing is being logged, no exceptions are being thrown and I wrapped both my call and line 33 in a try catch, and nothing is being caught. I am using Xcode 5 and have tried with both iOS 7 and iOS 6. I have renamed by variable to clientMasterId so it is no longer id. I am however using AFNetworking but that shouldn't make a difference.


I'm using AFNetworking with Xcode 5 and MR with no issues, so that's not it.

When you say you renamed the id attribute - this was in your core data model, and not the JSON, correct?


Can you see if this is fixed in the develop branch? I fixed something that looks just like this in the last two days.


Yes, I have confirmed that I have the develop branch. Are the values I pasted supposed to be nil?


I have also went ahead and added the userInfo for keymapping just to rule that out. Here is my setup. While stepping through I am noticing that it is looking for a lookupKey of providerSearchResultsID yet I do not have one in my attributes. Have I done something wrong?
screen shot 2013-08-21 at 6 51 18 pm


adding relatedByAttribute worked for me, even though the data model didn't yet have any relationships. Thanks!

@emadd emadd closed this

Just confirming that I had the same issue. I was crashing on line 33 of NSManagedObjectContext+MagicalRecord.m

Setting the relatedByAttribute on my entity fixed this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.