Pages

Core Data advanced queries with NSExpression Class

Fetching data from Core Data is very necessary && interesting to do because any application only storing the data  is only an overhead to the memory because all it can do is just to store the data in the memory but can't delete from it, can't fetch according to you expectations && eventually your application will crash due to shortage of memory. By using NSExpression class you can get data from database in any format you want. For example if you want to fetch the entries in such a manner which are entered in particular interval. You can do this by using NSExpression class to manually build predicates. A predicate contains two or more expressions and one or more comparator. Let us see through an example, you want to extract entries from database corresponding to attribute age in which age in between 20 to 30.
 let expressionAge = NSExpression(forKeyPath: "age")
 let expressionCompare1 = NSExpression(forConstantValue: "20")    
 let expressionCompare2 = NSExpression(forConstantValue: "30")
          //order matters here first 20 then 30
 let expressionCompare = NSExpression(forAggregate: [expressionCompare1, expressionCompare2])
 let predicateAge = NSComparisonPredicate(leftExpression: expressionAge, rightExpression: expressionCompare, modifier: NSComparisonPredicateModifier.AnyPredicateModifier, type: NSPredicateOperatorType.BetweenPredicateOperatorType, options: nil)

Here in the first expression we are creating an object of NSExpression class which will search the values in the age attribute stroked in database. The next two expressions are constant expressions which are the combined in third expression which in now composite && will search the database in attribute Age for entries whose age is between "20 to 30".
Now in fifth line we are creating a predicate which will compare the age attribute entries in core data to find the matched entries whose age is between 20 to 30 years. Now go ahead and combine this predicate 5th line to your fetch request which will fetch the entries from database.

fetchRequest.predicate = predicateAge

Here all this line doing is just prepare a fetch request corresponding to the predicate. Now add the code to execute the fetch request so that all the entries will be fetched corresponding to what we wanted.


let objects = persistence?.managedObjectContext?.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]

Here all this line of code is doing is fetching the entries of type NSManagedObject && storing into an array of type NSManagedObject.This is how you extract data from core data with NSExpression Class.

No comments:

Post a Comment