Skip to content

Instantly share code, notes, and snippets.

@keicoder
Last active August 29, 2015 13:55
Show Gist options
  • Save keicoder/8780552 to your computer and use it in GitHub Desktop.
Save keicoder/8780552 to your computer and use it in GitHub Desktop.
objective-c : CoreData : fetchRequest, sortDescriptor, filter using predicate, show resulting Array object using for loop
//sample code
//CoreData : fetchRequest, sortDescriptor, filter using predicate, show resulting Array object using for loop
- (void)demo {
if (debug==1) {NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));}
//데모 데이터
// NSArray *newItemNames = [NSArray arrayWithObjects:
// @"Apples", @"Milk", @"Bread", @"Cheese", @"Sausages", @"Butter", @"Orange Juice", @"Cereal", @"Coffee", @"Eggs", @"Tomatoes", @"Fish", nil];
//
// for (NSString *newItemName in newItemNames) {
// Note *newItem = [NSEntityDescription insertNewObjectForEntityForName:@"Note"
// inManagedObjectContext:_coreDataHelper.context];
// newItem.noteTitle = newItemName;
// NSLog(@"Inserted New Managed Object for '%@'", newItem.noteTitle);
// }
//fetchRequest
//NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Note"];
//fetchRequest using predefining fetch template
NSFetchRequest *request = [[[_coreDataHelper model] fetchRequestTemplateForName:@"Test"] copy];
//sortDescriptor
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"noteTitle" ascending:YES];
//request with sortDescriptor
[request setSortDescriptors:[NSArray arrayWithObject:sort]];
//filter using predicate (delete because now using predefining fetch template)
//NSPredicate *filter = [NSPredicate predicateWithFormat:@"noteTitle != %@", @"Coffee"];
//[request setPredicate:filter];
//resulting Array
NSArray *fetchedObjects = [_coreDataHelper.context executeFetchRequest:request error:nil];
//show resulting Array object using for loop
for (Note *item in fetchedObjects) {
NSLog(@"Fetched Object = %@", item.noteTitle);
}
}
//test code
- (void)applicationDidBecomeActive:(UIApplication *)application
{
if (debug==1) {NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));}
[self demo];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment