Skip to content

Instantly share code, notes, and snippets.

@john-07
Created April 24, 2015 07:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john-07/07f1615ec6a55bc676d2 to your computer and use it in GitHub Desktop.
Save john-07/07f1615ec6a55bc676d2 to your computer and use it in GitHub Desktop.
Core Data helpers
func fetchAll<T:NSManagedObject>(type:T.Type, predicate:NSPredicate?, sorts:[AnyObject]?=nil)->[T]{
let entityName = NSStringFromClass(type);
let request = NSFetchRequest(entityName:entityName);
request.predicate = predicate;
request.sortDescriptors = sorts;
var error:NSError?=nil;
if let rows = context.executeFetchRequest(request, error:&error) {
return rows as [T];
}else{
DDLogError("\(error)");
return [T]();
}
}
func fetchRow<T:NSManagedObject>(type: T.Type, predicate:NSPredicate?, sorts:[AnyObject]?=nil)->T?{
assert(NSThread.isMainThread());
let request = NSFetchRequest(entityName:NSStringFromClass(T));
request.predicate=predicate;
request.sortDescriptors = sorts;
request.fetchLimit=1;
var error:NSError?=nil;
if let rows = context.executeFetchRequest(request, error:&error) {
return rows.first as? T;
}else{
DDLogError("\(error)");
return nil;
}
}
@john-07
Copy link
Author

john-07 commented Apr 24, 2015

using:
let sort = NSSortDescriptor(key:"lastName", ascending:true);
let users = fetchAll(BMUser.self, predicate: predicate, sorts: [sort]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment