我想統一模型文件中特定類的所有功能。例如,我會在模型'Contact.h/Contact.m'中有一個函數fetchContactWithName:(NSString *)名稱,我的viewcontroller隨後會調用它。將AppDelegate導入模型?
在這種情況下,將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
好的答案,但單身也是一個壞主意。 – pbibergal
@pbibergal,爲什麼不呢? :) –
單身是反模式。它和全球一樣糟糕。 – pbibergal