How to execute a computed query using CoreData

I have a T-SQL background, so this CoreData stuff is a little bit for me.

I am creating a prototype application that will ultimately use the MS SQL web service to support queries.

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 do I make the same request in CoreData in my prototype using a predicate (if this is the best method)

NB its the more order that I became interested

+4
source share
1 answer

First make sure that Core Data is a hierarchy of objects in the first place. So you are not querying for columns, you're querying for objects.

With this, you need to build NSFetchRequest with NSPredicate , and the predicate will be something like strings:

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

You can also add sorting to NSFetchRequest , although you cannot perform calculations in sorting. Therefore, you can sort after the objects are retrieved.

Update

You may have a transient property on your objects, and then there is a method that says something like "-updateDistanceCalFrom: someFloat". Then using an array of objects you can 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]; 
+3
source

Source: https://habr.com/ru/post/1303565/


All Articles