仅更新NSManagedObject中的第一个对象

时间:2016-03-22 20:26:13

标签: objective-c nsmanagedobject

我想更新NSManagedObject中的第一条记录。我在这里更新了所有这些,我意识到这是因为我选择了所有这些并使用 for 更新它们,但我如何才更新第一条记录?

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Users"];
NSError *errorLoading = nil;
self.users = [context executeFetchRequest:fetchRequestNext error:& errorLoading];
for (NSManagedObject *usersObject in [self users])
{
   [usersObject setValue:@"*" forKey:@"currentUser"];
}
NSError *error;
[context save:&error3];
}

3 个答案:

答案 0 :(得分:2)

从结果(数组)中,您只需选择索引处的那个:0

NSArray *results = [context executeFetchRequest:fetchRequestNext error:& errorLoading];

if (results.count>0) {
    NSManagedObject *userObject = results[0];
    [usersObject setValue:@"*" forKey:@"currentUser"];
}
NSError *saveError = nil;
[context save:&saveError];

我希望这会有所帮助

答案 1 :(得分:1)

有点像这样:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Users"];
fetchRequest.fetchLimit = 1; //Fetch only one object (optional)

NSError *errorLoading = nil;
NSManagedObject *user = [[context executeFetchRequest:fetchRequestNext error:& errorLoading] firstObject];
if (errorLoading) {
    //handle error
}
[user setValue:@"*" forKey:@"currentUser"];
NSError *error = nil;
if (![context save:&error]) {
    //handle error
}

首先,如果你只需要一个对象,你可以将fetchLimit设置为1.这不是必需的,它只是一个小的优化(它会在获取第一个对象后使CoreData停止)。然后就像通常那样执行请求,并从结果数组中获取第一个对象。

答案 2 :(得分:0)

另一种选择是使用NSArray中定义的firstObject方法。

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Users"];
NSError *errorLoading = nil;
NSArray *users = [context executeFetchRequest:fetchRequestNext error:& errorLoading];

NSManagedObject *singleUser = [users firstObject];
if(singleUser){
    [singleUser setValue:@"*" forKey:@"currentUser"];
}

NSError *error;
if([context save:&error]){

}