您好,
我正在开发一个iphone应用程序,我必须借助核心数据NSPredicate
对象从sqlite表中获取数据。
我想在随机的基础上获取记录,而不进行任何排序。
喜欢:
SELECT * FROM zquestionsdata where zquestiontype='Logic' ORDER BY RANDOM()
如何通过NSPredicate
实施?
感谢.......
答案 0 :(得分:4)
你需要编写像这样的代码
-(NSMutableArray *)getRandomArrayFromDB
{
NSMutableArray *fetchResults;
NSString *entityName=@"questionsdata";
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:globalManagedObjectContext];
[fetchRequest setEntity:entity];
fetchResults = [NSMutableArray arrayWithArray:[globalManagedObjectContext executeFetchRequest:fetchRequest error:nil]];
[fetchRequest release];
NSString *cat=@"Logic";
[fetchResults filterUsingPredicate:[NSPredicate predicateWithFormat:@"questiontype == %@",cat]];
// sort it in random order
NSUInteger count = [fetchResults count];
for (NSUInteger i = 0; i < count; ++i) {
// Select a random element between i and end of array to swap with.
int nElements = count - i;
int n = (random() % nElements) + i;
[fetchResults exchangeObjectAtIndex:i withObjectAtIndex:n];
}
return fetchResults;
}
调用此方法,它可以提供您想要的内容。