Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFetchedResultsController returns duplicates (the same objectID and reference)

I'm experiencing a weird behaviour with NSFetchedResultsController. It is new in iOS 10. Straight to the point: fetchedObjects contains duplicate objects.

This is not by any mean "duplicate" in my own criteria. They literally have the same objectIDs and the same reference.

How does it happen in my app:

  1. FRC is setup and fetch performed

  2. 2 objects are fetched (in this example)

  3. Something happens in my sync layer, another object (that fetch items are in relationship with) is updated

  4. FRC calls delegate that the content did change. fetchedObjects contains 4 objects (2 duplicates)

Here's a console output from my debugging in controllerDidChangeContent method.

po frc.fetchedObjects

    - 0 : <ListItem: 0x1700dc3f0> (entity: ListItem; id: 0x1706294a0 <x-coredata://12D0CB00-7BF4-402A-8371-19DD1CFB1537/ListItem/t3384FC2D-3399-41FE-B7DD-C277922F495445> ; data: { ... }

    - 1 : <ListItem: 0x1700dc3f0> (entity: ListItem; id: 0x1706294a0 <x-coredata://12D0CB00-7BF4-402A-8371-19DD1CFB1537/ListItem/t3384FC2D-3399-41FE-B7DD-C277922F495445> ; data: { ... }

    - 2 : <ListItem: 0x1704c49f0> (entity: ListItem; id: 0x170631680 <x-coredata://12D0CB00-7BF4-402A-8371-19DD1CFB1537/ListItem/t3384FC2D-3399-41FE-B7DD-C277922F495446> ; data: { ... }

    - 3 : <ListItem: 0x1704c49f0> (entity: ListItem; id: 0x170631680 <x-coredata://12D0CB00-7BF4-402A-8371-19DD1CFB1537/ListItem/t3384FC2D-3399-41FE-B7DD-C277922F495446> ; data: { ... }


(lldb) po frc.fetchedObjects![0].objectID.isEqual(frc.fetchedObjects![1].objectID)
true

Another note: when I recreate FRC and fetch objects again, there are no duplicates.

I simply have no idea what could be causing this problem. I might be doing something wrong in my app that is causing that bug. It's really weird anyway that FRC allows for duplicates objects in fetchedObjects. Can you please give me any clue of how should I debug it?

like image 956
msmialko Avatar asked Sep 28 '16 11:09

msmialko


1 Answers

I've come across similar problem today also. I noticed in my case the fetched objects on the FRC all had temporary IDs. These can be verified like so:

fetchedResultsController.fetchedObjects[0].objectID.isTemporary

To get around this problem in my App I explicitly request permanent object IDs for all the inserted objects before saving the context on which new data is imported/updated/synced:

NSError *error;
[bgContext obtainPermanentIDsForObjects:bgContext.insertedObjects.allObjects error:&error];
like image 64
AlexYu Avatar answered Nov 02 '22 09:11

AlexYu