4

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 * FROM zquestionsdata where zquestiontype='Logic' ORDER BY RANDOM() 

How can it be implemented by NSPredicate?

Thanks.......

Mutix
  • 4,196
  • 1
  • 27
  • 39
Lalit Paliwal
  • 723
  • 2
  • 10
  • 19
  • This post could help you. http://stackoverflow.com/questions/2063050/how-to-sort-randomly-with-coredata –  Jul 05 '11 at 06:25

1 Answers1

4

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.

Ishu
  • 12,797
  • 5
  • 35
  • 51