NSDictionary不会填满

时间:2012-10-04 10:28:16

标签: objective-c ios core-data nsdictionary

我有以下代码。

-(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 );

它提供了正确的数据。

有人可以帮忙吗?

亲切的问候。

2 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分:1)

确保使用以下代码行在某处实例化了_photos词典:

_photos = [[NSMutableDictionary alloc] init];

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