Search code examples
objective-ccore-datanspredicatensfetchrequestmagicalrecord

NSFetchRequest query returns nil after setting one to many relationship


I have two NSManagedObject subclasses, Book and Category. The two are related by one-to-many relationship.

On Book side, it has relationship categories connected to Category. Inversely Category connected to Book via books.

My app setup is to download the data from my server every time the app opened. The downloaded data will be traversed and save inside the app. In my app, I use Magical Record to interact with CoreData.

Category data will first be downloaded and later saved from JSON format:

{
    "categories" : [
        {
            "id" : 1,
            "name" : "Fiction"
        },
        {
            "id" : 2,
            "name" : "Non-fiction"
        }
    ]
}

There has been no problem on saving Category. While later on the app lifecycle Book data will be saved from JSON format as following:

{
    "books" : [
        {
            "id" : 1,
            "name" : "Fiction 1",
            "category_id" : 1
        },
        {
            "id" : 2,
            "name" : "Fiction 2",
            "category_id" : 2
        }
    ]
}

The problem arises when I want to assign Book relation to Category. My code to assign the relationship:

for (NSDictionary *bookInfo in jsonObject[@"books"]) {
    Book *book = [Book createEntity];
    book.identifier = bookInfo[@"id"];
    book.name = bookInfo[@"name"];

    Category *category = [Category findFirstByAttribute:@"identifier" withValue:bookInfo[@"category_id"]];

    book.category = category;

    [[NSManagedObjectContext contextForCurrentThread] saveNestedContexts];
}

On the first loop, the bookObject was saved successfully. But on the second loop and next, the Category cannot be queried anymore. It returns nil, despite the identifier is the same.

I did perform check on all the Category via [Category findAll] and traversed all the records and found that the Category with the same id still exist on the second and next loop.

The question is why is the findFirstByAttribute:withValue: failed to retrieve Category on the second loop?


Solution

  • I fixed this problem by updating MagicalRecord to the latest version (2.1).

    And then I modified the way my NSManagedObject saving method from saveNestedContexts to newly added saveUsingCurrentThreadContextWithBlockAndWait.