views:

373

answers:

4

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.

+1  A: 

There is an acticle comparing the Windows and Cocoa ways of doing this. Cocoa uses Key Paths And NSPredicate....

Cocoa is my Girlfriend

Tony Lambert
+1  A: 

I think specific to your example this would be the equivalent in Cocoa:

NSArray *people = /* array of people objects */

NSPredicate *pred = [NSPredicate predicateWithFormat:@"Id = 1 AND Id != 2"];
NSSortDescriptor *byName = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObject:[byName autorelease]];

NSArray *matches = [people filteredArrayUsingPredicate:pred];
NSArray *sortedMatches = [matches sortedArrayUsingDescriptors:descriptors];

NSArray *justNames = [sortedMatches valueForKey:@"Name"];

It's a little more verbose than the LINQ example and some of my lines could have been combined but to my eye this is easier to parse.

Ashley Clark
A: 

Mmm ok, but then how apply it to a Sqlite query and not a fully loaded array?

mamcx
That really depends on how you'll be communicating with the sqlite library.
Ashley Clark
+2  A: 

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];
slf