Order by custom () article in iphone NSPredicate

Hello,

I am working on an iphone application and I have to fetch data from sqlite table using the main NSPredicate object.

I want to get entries on a random basis without sorting.

Like:

 SELECT * FROM zquestionsdata where zquestiontype='Logic' ORDER BY RANDOM() 

How can this be implemented using NSPredicate ?

Thanks.......

+4
source share
1 answer

You need to write something 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.

+4
source

All Articles