只更新 NSManagedObject 中的第一个对象

Updating only the first object in 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];
}

有点像这样:

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在获取第一个对象后停止) .然后像往常一样执行请求并从结果数组中获取第一个对象。

从结果(数组)中,您只需 select index: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];

希望对您有所帮助

另一种选择是使用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]){

}