开发者

How do I perform a calculated query using CoreData

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 - long开发者_运维百科itude))

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜