Core Data data access pattern?
It seems crazy to me that I have all of these NSFetchRequests for the same NSManagedObjects spread out throughout different view controllers in my app, is ther开发者_开发技巧e a good pattern for data access that puts what I need in a single place?
I agree it is a bit much, fortunately there is Active Record for Core Data. This makes fetching less tedious, for example, fetching all Person objects from core data would be as simple as
NSArray *people = [Person findAll];
Yes there is, it is called a facade pattern. Simply define a public method on your NSManagedObject
subclass like so:
@interface Group : NSManagedObject { }
// … cruft here …
-(NSArray*)peopleSortedByName;
@end
And hide the nasty implementation like so:
-(NSArray*)peopleSortedByName;
{
NSFetchRequest* request = // … bla bla, lots of code here
return [[self managedObjectContext] executeFetchRequest:request
error:NULL];
}
Then use the method just as if the it was any other class in your code. Write once, relief everywhere.
Define a category method for NSManagedObject context which wrappers up a general query into a one-liner.
@interface NSManagedObjectContext(MyQueryAdditions)
-(NSArray *)queryEntityForName:(NSString *)name predicateFormat:(NSString *)pstring argumentArray:(NSArray *)arr;
@end
@implementation NSManagedObjectContext(MyQueryAdditions)
-(NSArray *)queryEntityForName:(NSString *)name predicateFormat:(NSString *)pstring argumentArray:(NSArray *)arr
{
NSEntityDescription *entity = [NSEntityDescription entityForName:name inManagedObjectContext:self];
NSFetchRequest *fetch = [[[NSFetchRequest alloc] init] autorelease];
[fetch setEntity:entity];
NSPredicate *pred;
if(pstring)
{
if(arr) pred = [NSPredicate predicateWithFormat:pstring argumentArray:arr];
else pred = [NSPredicate predicateWithFormat:pstring];
[fetch setPredicate:pred];
}
NSError *error = nil;
[self retain];
[self lock];
NSArray *results = [self executeFetchRequest:fetch error:&error];
if (error) {
NSLog(@"MOC Fetch - Unresolved error %@, %@", error, [error userInfo]);
results = [NSArray array];
}
[self unlock];
[self release];
return results;
}
@end
Means a basic all items query can be as simple as
NSArray *cres = [managedObjectContext queryEntityForName:@"Person" predicateFormat:nil argumentArray:nil];
精彩评论