Search code examples
objective-ccore-datansfetchrequest

Core data fetch data which actually stored in persistentStore not all objects of entities (persistentStored + latest created obj)


I have one entity name is student and I want fetch those student data which lives in Pune city (city == pune). In table there are 2 students who lives in pune city.

But before that I have create new student object who lives also in pune city.

So when I fire fetch request on student entity its give me 3 student data which included my current student data also (2 from table and 1 which I just created not saved in table)

So my question is I just want only those student data which I actually stored in persistence data not those which are just created.

Entity data (student)
--------------------------------------------------------
student name       city         class
--------------------------------------------------------
Atul               pune           7
Sagar              mumbai         7
Ganesh             pune           7
--------------------------------------------------------

current object

Student * obj = [[Mlov alloc] initWithEntity:[NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.managedObjectContext] insertIntoManagedObjectContext:self.managedObjectContext];


    obj.name = @"Nitin";
    obj.city = @"pune";
    obj.class = 10;
     NSError * error = nil;

    NSPredicate * pred = [NSPredicate predicateWithFormat:@"city == 'pune'"];


    NSFetchRequest * req = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
    [req setReturnsObjectsAsFaults:NO];
    [req setPredicate:pred];
    NSError * error = nil;
    NSArray * result =[context executeFetchRequest:req error:nil];
    for (Student * obj in result)
    NSLog(@"%@",obj.name); 

Expected output as only 2 students data (Atul and Ganesh)

Actually giving output as 3 students data (Atual, Ganesh and Nitin)

I need to fetch those student data which are stored in persistence store, If you have any suggestion please let me know. Thanks in advance.


Solution

  • Solution 1

    You could filter out objects which appear in the context's insertedObjects property.

    [result filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"NOT SELF IN %@",
                                                                         context.insertedObjects]];
    

    Solution 2

    Use a fresh context for the query.