我有一个实体名为 student ,我想获取生活在浦那市(城市== pune)的学生数据。桌子上有2学生,他们住在pune市。
但在此之前,我已经创建了新的学生对象,他也住在浦那市。
因此,当我对学生实体发出获取请求时,它给了我3个学生数据,其中还包括我当前的学生数据(2个来自表,1个刚刚创建,没有保存在表中)
,所以我的问题是,我只想要那些实际存储在持久性数据中的学生数据,而不是那些刚刚创建的.。
Entity data (student)
--------------------------------------------------------
student name city class
--------------------------------------------------------
Atul pune 7
Sagar mumbai 7
Ganesh pune 7
--------------------------------------------------------当前对象
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)我需要获取存储在持久性存储中的学生数据,如果您有任何建议,请告诉我。提前谢谢。
发布于 2015-12-01 10:57:55
解决方案1
您可以筛选出出现在上下文的insertedObjects属性中的对象。
[result filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"NOT SELF IN %@",
context.insertedObjects]];解决方案2
对查询使用新的上下文。
https://stackoverflow.com/questions/34018035
复制相似问题