Created
December 18, 2014 15:53
-
-
Save jamesktan/2463ae9a08869a6631b9 to your computer and use it in GitHub Desktop.
iOS : Core Data - Get Core Data Objects by Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSManagedObjectContext *context = <#Get the context#>; | |
NSFetchRequest *request = [[NSFetchRequest alloc] init]; | |
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>" inManagedObjectContext:context]; | |
[request setEntity:entity]; | |
// Specify that the request should return dictionaries. | |
[request setResultType:NSDictionaryResultType]; | |
// Create an expression for the key path. | |
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"<#Key-path for the property#>"]; | |
// Create an expression to represent the function you want to apply | |
NSExpression *expression = [NSExpression expressionForFunction:@"<#Function name#>" | |
arguments:@[keyPathExpression]]; | |
// Create an expression description using the minExpression and returning a date. | |
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init]; | |
// The name is the key that will be used in the dictionary for the return value. | |
[expressionDescription setName:@"<#Dictionary key#>"]; | |
[expressionDescription setExpression:expression]; | |
[expressionDescription setExpressionResultType:<#Result type#>]; // For example, NSDateAttributeType | |
// Set the request's properties to fetch just the property represented by the expressions. | |
[request setPropertiesToFetch:@[expressionDescription]]; | |
// Execute the fetch. | |
NSError *error; | |
id requestedValue = nil; | |
NSArray *objects = [context executeFetchRequest:request error:&error]; | |
if (objects == nil) { | |
// Handle the error. | |
} | |
else { | |
if ([objects count] > 0) { | |
requestedValue = [[objects objectAtIndex:0] valueForKey:@"<#Dictionary key#>"]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment