我正在尝试统一模型文件中特定类的所有功能。例如,我将在模型“Contact.h/Contact.m”中有一个函数 fetchContactWithName:(NSString *)name,我的视图控制器随后会调用它。
在这种情况下,将 AppDelegate.h 文件导入模型文件是不是一个坏主意,因为我需要访问它的 managedObjectContext?
#import "AppDelegate.h"
@implementation Contact
...
+ (Contact *) fetchContactWithName:(NSString *) name {
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:delegate.managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", name];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
NSArray *fetchedObjects = [delegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
Contact *fetchedContact;
for(Contact *contact in fetchedObjects) {
fetchedContact = contact;
}
if(fetchedContact != nil) {
return fetchedContact;
} else {
return nil;
}
}
@end