使用谓词过滤NSArray会留下额外的结果吗?

时间:2013-07-04 16:37:22

标签: objective-c arrays sorting core-data nspredicate

我有一个包含NSDictionary对象的NSArray。

我需要根据选择的值过滤对象,所以我创建了一个我希望过滤的值的数组,并使用了predicatewithformat并将其提供给对象数组。

这有点工作,但奇怪的是在我知道我应该得到一个空数组返回的情况下我得到一个单独的对象,不应该在那里。

我已经注销了过滤器值数组的值,我可以清楚地看到它包含一个与对象的id_str对应的键,因此不应该返回。

下面是我正在使用的代码,任何指向我出错的地方都会非常有用!

                 //Create new fetch request
             NSFetchRequest *request = [[NSFetchRequest alloc] init];

             //Set new predicate to only fetch tweets that have been favourited
             NSPredicate *filterFavourite = [NSPredicate predicateWithFormat:@"favouriteTweet == 'YES'"];

             //Setup the Request
             [request setEntity:[NSEntityDescription entityForName:@"Tweet" inManagedObjectContext:_managedObjectContext]];

             //Assign the predicate to the fetch request
             [request setPredicate:filterFavourite];
             NSError *error = nil;

             //Create an array from the returned objects
             NSArray *favouriteTweets = [_managedObjectContext executeFetchRequest:request error:&error];
             NSAssert2(favouriteTweets != nil && error == nil, @"Error fetching events: %@\n%@", [error localizedDescription], [error userInfo]);

             //Create a new array containing just the tweet ID's we are looking for
             NSArray *favouriteTweetsID = [favouriteTweets valueForKey:@"tweetID"];

             NSLog(@"%@", favouriteTweetsID);

             //Create a new predicate which will take our array of tweet ID's
             NSPredicate *filterFavouritsearchPredicate = [NSPredicate predicateWithFormat:@"(id_str != %@)" argumentArray:favouriteTweetsID];

             //Filter our array of tweet dictionary objects using the array of tweet id's we created
             NSArray *filteredTweets = [self.timelineStatuses filteredArrayUsingPredicate:filterFavouritsearchPredicate];

             //Send those tweets out to be processed and added to core data
            [self processNewTweets:filteredTweets];

             NSLog(@"Update Favoutited Tweets: %@", filteredTweets);

1 个答案:

答案 0 :(得分:4)

这可能不符合您的意图:

[NSPredicate predicateWithFormat:@"(id_str != %@)" argumentArray:favouriteTweetsID];

相当于

[NSPredicate predicateWithFormat:@"(id_str != %@)", id1, id2, ... idN];

其中id1,id2,...,idN是favouriteTweetsID的元素。 格式字符串只有一个格式说明符,  所以一切都没有 第一个元素被忽略,你只有

[NSPredicate predicateWithFormat:@"(id_str != %@)", id1];

如果要过滤id_str不等于任何数组元素的所有对象, 使用

[NSPredicate predicateWithFormat:@"NOT id_str IN %@", favouriteTweetsID];