coredata获取特定项目 - ios

时间:2015-12-04 08:51:00

标签: ios objective-c

我是目标c的新手。我已将记录保存在核心数据中。

我想获取具有alternate_id = 523的记录。

如何在核心数据中实现这一目标

2 个答案:

答案 0 :(得分:0)

有类似的东西:

AppDelegate* app = (AppDelegate*)[UIApplication sharedApplication].delegate;
MyEntity* entity = nil;
NSInteger myID = 523;

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity: [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:app.managedObjectContext]];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"alternate_id = %@",@(myID)];
[request setPredicate:predicate];
NSArray* array = [app.managedObjectContext executeFetchRequest:request error:nil];
if([array count] > 0)
{
    entity = [array objectAtIndex:0];
}

答案 1 :(得分:0)

NSError *error = nil;

NSManagedObjectContext *managedObjectContext = [Your managedContext];

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"YourEntityName" inManagedObjectContext:managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];

[request setEntity:entityDescription];

NSPredicate *predicateObj = [NSPredicate predicateWithFormat:@"(alternate_id ==%@)", @"523"];

[request setPredicate:predicateObj];

NSArray *resultArray = [managedObjectContext executeFetchRequest:request error:&error];

YourEntity *yourEntityObj = nil;

if (resultArray && [resultArray count]>0) {
    yourEntityObj =  [resultArray objectAtIndex:0];
}