0

我有以下一段代码。

-(NSDictionary *)getPlayers
{

    NSManagedObjectContext *context = self.genkDatabase.managedObjectContext;

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Team"
                                              inManagedObjectContext:context];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"position ==[c] %@", @"Doelman"];
    [fetchRequest setEntity:entity];

    NSError *error;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        // Handle the error.
    }else

        for (Team *info in fetchedObjects) {

            [_photos setObject:info.image  forKey:@"player_imgUrl"];
            [_photos setObject:info.name forKey:@"player_name"];


        }
    NSLog(@"%@",_photos);
    return _photos;

但出于某种原因,我的 NSLog 总是返回 (null)。但是当我这样做时

[_photos setObject:info.image  forKey:@"player_imgUrl"];
            [_photos setObject:info.name forKey:@"player_name"];

            NSLog(@"name: %@",info.name );
            NSLog(@"url: %@",info.image );

它会返回正确的数据。

有人可以帮忙吗?

亲切的问候。

4

2 回答 2

1

您有一个错误,可能与问题没有直接关系。在 for 循环中,您总是为同一个键重置名称和图像。所以在循环结束时,您的字典必须有一个名称和一个图像,而不是数组中的所有名称。你应该改变它

更新:可能是这样的:

int count = fetchedObjects.count;

for (int i = 0; i < count; i++)
{
   NSString *image_key = [NSString stringWithFormat:@"player_imgUrl%d",i];
   NSString *name_key =  [NSString stringWithFormat:@"player_name%d",i];

  [_photos setObject:[[fetchedObjects objectAtIndex:i] image]  forKey:image_key];
  [_photos setObject:[[fetchedObjects objectAtIndex:i] name] forKey:name_key];
}
于 2012-10-04T10:35:01.460 回答
1

确保您已使用以下代码行在某处实例化您的 _photos 字典:

_photos = [[NSMutableDictionary alloc] init];

仅仅将其定义为实例变量或属性是不够的。

于 2012-10-04T10:38:13.300 回答