开发者

Order by Random() clause in iphone NSPredicate

Hi,

I am working on an iphone app, and I have to fetch out data from sqlite table with the help of core data NSPredicate object.

I want to fetch records on Random basis, without any sorting.

Like :

SELECT 开发者_如何学Go* FROM zquestionsdata where zquestiontype='Logic' ORDER BY RANDOM() 

How can it be implemented by NSPredicate?

Thanks.......


You need to write code some thing like this

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

call this method and it gives what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜