1

我正在从CoreData我期望的地方1 resultnil.

目前我将 fetch 设置为 aNSArray并且我尝试将其提取到一个IconRoutine*对象中,但[context executeFetchRequest:fetchIcon error:&error];需要提取到一个数组中,因此在我尝试这样做时会导致崩溃。

我想我想知道我是否可以以另一种方式获取 aentity object以便我不需要if ( [Icon count] !=0 )检查 anil并且我可以返回获取的任何内容并nil entity在另一种方法中处理。

或者也许只是一种更有效的方式(如果有的话)来处理您期望的结果1nil.

- (IconRoutine *) getIconRoutine {

    NSFetchRequest *fetchIcon = [[NSFetchRequest alloc] init];
    NSEntityDescription *entityItem = [NSEntityDescription entityForName:@"IconRoutine" inManagedObjectContext:context];
    [fetchIcon setEntity:entityItem];

    [fetchIcon setRelationshipKeyPathsForPrefetching:[NSArray arrayWithObjects:@"User",@"Routine", nil]];

    [fetchIcon setPredicate:[NSPredicate predicateWithFormat:@"(routine.routineName == %@) AND (user.email LIKE %@) AND (author LIKE %@)",_routineNameInput.text,_appDelegate.currentUser,_routineAuthor]];

    NSError *error = nil;
    NSArray* Icon = [context executeFetchRequest:fetchIcon error:&error];

    if ( [Icon count] !=0 ) {
        return Icon[0];
    }
    return NO;    
}
4

1 回答 1

1

这是一个选项。不一定是您正在寻找的解决方案,但可能会有所帮助:

- (IconRoutine *) getIconRoutine {

    NSFetchRequest *fetchIcon = [[NSFetchRequest alloc] init];
    NSEntityDescription *entityItem = [NSEntityDescription entityForName:@"IconRoutine" inManagedObjectContext:context];
    [fetchIcon setEntity:entityItem];

    [fetchIcon setRelationshipKeyPathsForPrefetching:[NSArray arrayWithObjects:@"User",@"Routine", nil]];

    [fetchIcon setPredicate:[NSPredicate predicateWithFormat:@"(routine.routineName == %@) AND (user.email LIKE %@) AND (author LIKE %@)",_routineNameInput.text,_appDelegate.currentUser,_routineAuthor]];

    return [context executeFetchRequest:fetchIcon error:nil].lastObject;    
}

这显然仅在您不关心错误消息时才有效。如果是 nil 或数组为空(所以永远不会) lastObject,将返回 nil !否则,它将返回最后一个对象,如果只有一个对象,它只会返回那个。NSArrayindexOutOfBoundsException

如果您确实关心错误,您可以简单地执行以下操作:

- (IconRoutine *) getIconRoutine {

    // fetch code from above
    // ..    

    NSError *fetchError
    IconRoutine *result = [context executeFetchRequest:fetchIcon error:&fetchError].lastObject;

    if (fetchError) {
        // handle the error
    }

    // return whatever result is anyway because if there was an error it would already be nil, and if not then it is the object you are looking for
    return result;
}

希望这可以帮助!

于 2013-06-07T16:28:05.720 回答