executeFetchRequest将NSPredicate设置为NSFetchRequest后崩溃

时间:2014-12-08 00:23:21

标签: ios sql regex core-data nspredicate

我真的被这个问题困住了,我把这个生锈的SQL / REGEX归咎于这个,但我希望你能帮忙。

我有这个CoreData实体:

@interface Movie : NSManagedObject

@property (nonatomic, retain) id genreArray;
@property (nonatomic, retain) NSNumber * imdbID;
@property (nonatomic, retain) NSNumber * isPlaying;
@property (nonatomic, retain) NSNumber * isPromo;
@property (nonatomic, retain) NSNumber * isTickets;
@property (nonatomic, retain) NSDate * lastUpdate;
@property (nonatomic, retain) NSNumber * movieID;
@property (nonatomic, retain) NSString * movieName;
@property (nonatomic, retain) NSString * movieName_EN;
@property (nonatomic, retain) id movieOtherNames;
@property (nonatomic, retain) NSString * posterPicture;
@property (nonatomic, retain) etcetcetc;

@end

所以,我想通过NAME搜索一部电影。问题是名称可以在movieName或movieName_EN下,也可以在数组movieOtherNames中的一个名称中。

目前,我徒劳的要求是这样的:

    Movie* movie = nil;

    NSEntityDescription *allMovs = [NSEntityDescription entityForName:@"Movie"
                                                inManagedObjectContext:[self mainManagedObjectContext]];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:allMovs];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                        initWithKey:@"premiereDate" ascending:NO];
    [request setSortDescriptors:@[sortDescriptor]];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"$movieName contains[cd] %@ OR %@ contains[cd] $movieName OR $movieName_EN contains[cd] %@ OR  %@ contains[cd] $movieName_EN OR ANY $movieOtherNames MATCHES %@", movieName, movieName, movieName, movieName, movieName];
    [request setPredicate:predicate];
    NSError *error;
    NSArray* moviesArray = [[self mainManagedObjectContext] executeFetchRequest:request error:&error];
    if(error)
        SRTLog(@"CoreData: NO movieTimes! Deal with error...");
    if([moviesArray count] > 0)
        movie = [moviesArray objectAtIndex:0];
    return movie;

我的应用在执行此代码时崩溃了。我的猜测是NSPredicate。那里有些东西非常错误。

任何人都可以帮我解决如何搜索可以包含(或包含)2个字段和字符串数组的字符串吗?

我会为那些愿意提供帮助的善良灵魂提供Stack OverFlow。

1 个答案:

答案 0 :(得分:1)

我认为你的这个谓词有点不对劲。如果解决了这个问题,请尝试实现此功能。如果没有,请求添加一些错误描述和确切的行。

我希望代码本身是自我解释的:

    NSString *movieName = @""; // get the true name value
    NSArray *predicateCompounds = @[
                                    [NSPredicate predicateWithFormat:@"movieName LIKE[cd] %@", movieName],
                                    [NSPredicate predicateWithFormat:@"%@ LIKE[cd] movieName", movieName],
                                    [NSPredicate predicateWithFormat:@"movieName_EN LIKE[cd] %@", movieName],
                                    [NSPredicate predicateWithFormat:@"%@ LIKE[cd] movieName_EN", movieName]
                                    ];
    NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:predicateCompounds];