views:

73

answers:

1

I have an T-SQL background so this CoreData stuff is a little new to me.

I am prototyping an app which will eventually use an MS SQL backend webservice for querying.

In my backend my t-sql query would be something like this:

SELECT *, SQRT(SQUARE(myX - latitude) + SQUARE(myY - longitude)) Distance
FROM Locations 
WHERE latitude > myX 
AND latitude < myX + deltaX
AND longitude >  myX 
AND latitude < myY + deltaY
ORDER BY SQRT(SQUARE(myX - latitude) + SQUARE(myY - longitude))

How would I do this same query in CoreData in my prototype using a predicate (if thats the best method)

N.B. its more the order by that Im interested in

+2  A: 

First, realize that Core Data is an object hierarchy first and foremost. Therefore you do not request columns, you request objects.

With that, you would want to construct a NSFetchRequest with a NSPredicate and the predicate would be something along the lines of:

[NSPredicate predicate withFormat:@"latitude > %@ AND latitude < %@ AND 
  longitude > %@ and longitude < %@", someFloatObject1, someFloatObject2, 
  someFloatObject3, someFloatObject4];

You can also add a sort to the NSFetchRequest although you cannot do calculations within the sort. Therefore you may want to perform the sort after the objects are fetched.

update

You can have a transient property on your objects and then have a method that says something like '-updateDistanceCalFrom:someFloat`. Then, with an array of objects you could do the following:

NSArray *myFetchedArray = ...
[myFetchedArray makeObjectsPerformSelector:@(updateDistanceCalcFrom:)
                                withObject:someFloatObject];
NSSortDescriptor *calcSort = ...;
NSArray *descriptors = [NSArray arrayWithObject:calcSort];
[calcSort release], calcSort = nil;
NSArray *sortedArray = [myFetchedArray sortedArrayUsingDescriptors:descriptors];
Marcus S. Zarra
Thanks Marcus, I realise it is an OO world but that said I am wanting to query properties of my objects, I understand all the code you entered above and already have things working that far. The main problem is the sorting based upon a calcualted field, I don't think it will be that easy. Could I perform a query against a property on my object is a method called distanceFromObject:myX:myY??
tigermain