Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something similar to LINQ in Objective-C?

Tags:

I wonder if it is possible (and how) to provide a class in Objective-C with something like:

Person.Select(@"Name").OrderAsc(@"Name").Where(@"Id").EqualTo(1).And(@"Id").NotEqualTo(2).Load<Array>

That could be very handy for a project I'm doing.

I like this way of coding present in Django & SubSonic.

like image 890
mamcx Avatar asked Jan 09 '09 15:01

mamcx


Video Answer


2 Answers

I created my own Linq-style API for Objective C, which is available on github. Your specific example would look something like this:

NSArray* results = [[[people where:^BOOL(id person) {
                                return [person id] == 1 && [person id] != 2;
                             }]
                             select:^id(id person) {
                                return [person name];
                             }]
                             sort]; 
like image 170
ColinE Avatar answered Sep 21 '22 06:09

ColinE


The short answer is that there is not an equivalent to Linq for Objective-C but you can fake it with a mix of SQLite, NSPredicate and CoreData calls in a wrapper class shaped to your liking. You'd probably be interested in the core data guide, the predicate guide, and this example code.

From the above predicate guide:

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Employee"
        inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
// assume salaryLimit defined as an NSNumber variable
NSPredicate *predicate = [NSPredicate predicateWithFormat:
        @"salary > %@", salaryLimit];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];
like image 29
slf Avatar answered Sep 21 '22 06:09

slf