NSPredicate总是返回相同的数据

时间:2012-10-15 22:54:35

标签: objective-c ios nspredicate nsfetchrequest

我正在努力与NSPredicates合作。但它总是让我回到相同的阵列。在这里你可以看到我的谓词。

NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"whichAlbum.album_id == %d", AlbumId];
    [request setEntity:[NSEntityDescription entityForName:@"Picture" inManagedObjectContext:self.genkDatabase.managedObjectContext]];
    [request setPredicate:predicate];

当我尝试硬编码的时候。它返回相同的数组。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"whichAlbum.album_id == 5"];

我的数据库模型是:

enter image description here

在这里你可以看到我如何将数据放入我的数据库中实体图片。

+ (Picture *)pictureWithGenkInfo:(NSDictionary *)genkInfo
          inManagedObjectContext:(NSManagedObjectContext *)context
                     withAlbumId:(int)albumId
                   withPictureId:(int)pictureId;
{

    Picture *picture = nil;

    picture = [NSEntityDescription insertNewObjectForEntityForName:@"Picture"
                                          inManagedObjectContext:context];
    picture.url                     = [genkInfo objectForKey:PICTURES_URL];
    picture.pic_album_id            = [NSNumber numberWithInt:albumId];
    picture.picture_id              = [NSNumber numberWithInt:pictureId];


    return picture;
}

任何人都可以帮助我?

亲切的问候 的修改

  for (NSDictionary *genkInfo in albums ) {
        albumId++;
        Album *album = [Album albumWithGenkInfo:genkInfo inManagedObjectContext:document.managedObjectContext withAlbumId:albumId];
        for (NSDictionary *genkInfo2 in pictures ) {
            pictureId++;
            Picture *pic = [Picture pictureWithGenkInfo:genkInfo2 inManagedObjectContext:document.managedObjectContext withAlbumId:albumId withPictureId:pictureId];
            [album addPicturesObject:pic]; // this method should be automatically generated
        }
        pictureId = 0;
        // table will automatically update due to NSFetchedResultsController's observing of the NSMOC
    }

2 个答案:

答案 0 :(得分:0)

只需删除whichAlbum并尝试:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"album_id == %d", AlbumId];

答案 1 :(得分:0)

更好的是,假设AlbumId的值是某种数字原语:

old style:
[NSPredicate predicateWithFormat:@"whichAlbum == %@", [NSNumber numberWithInt:AlbumId]];
modern style: (xcode 4.5)
[NSPredicate predicateWithFormat:@"whichAlbum == %@", @(albumId)];

由于looks like predicateWithFormat:可能只会在其格式字符串中生成%@@K的正确谓词。

最佳:假设您有权访问您尝试匹配的相册管理对象,请尝试以下操作:

[NSPredicate predicateWithFormat:@"whichAlbum == %@", album];

匹配对象,而不是其中一个属性