我有这两个类方法,每个方法都带有它的谓词。它们的功能是保存将在mapKit和UITable View中显示的信息。但我看到重复的代码,除了谓词;我的问题是:我怎样才能避免这些重复?
+ (NSArray*)spotType:(NSString*)type{
NSPersistentContainer *persistenceContainer = [AppDelegate sharedDelegate].persistentContainer;
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"type =%@", type];
NSManagedObjectContext *context = persistenceContainer.viewContext;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Spot"];
[request setPredicate:predicate];
NSError *error;
NSArray *result = [context executeFetchRequest:request error:&error];
if (error != nil) {
NSLog(@"[Spot spotType] -> %@", [error localizedDescription]);
return nil;
}
return result;
}
+ (NSArray*)spotWithType:(NSString*)type{
NSPersistentContainer *persistenceContainer = [AppDelegate sharedDelegate].persistentContainer;
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"NOT (type = %@)", type];
NSManagedObjectContext *context = persistenceContainer.viewContext;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Spot"];
[request setPredicate:predicate];
NSError *error;
NSArray *result = [context executeFetchRequest:request error:&error];
if (error != nil) {
NSLog(@"[Spot spotWithType] -> %@", [error localizedDescription]);
return nil;
}
return result;
}
答案 0 :(得分:1)
减少代码重复的最基本方法是将公共代码放入共享私有方法中:
- (NSArray*)getSpotType:(NSString*)type withPredicate:(NSString*) pred andMessage:(NSString*)message {
NSPersistentContainer *persistenceContainer = [AppDelegate sharedDelegate].persistentContainer;
NSPredicate* predicate = [NSPredicate predicateWithFormat:pred, type];
NSManagedObjectContext *context = persistenceContainer.viewContext;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Spot"];
[request setPredicate:predicate];
NSError *error;
NSArray *result = [context executeFetchRequest:request error:&error];
if (error != nil) {
NSLog(message, [error localizedDescription]);
return nil;
}
return result;
}
- (NSArray*)spotType:(NSString*)type {
return [MyClass getSpotType:type withPredicate:@"type =%@" andMessage:@"[Spot spotType] -> %@"];
}
- (NSArray*)spotWithType:(NSString*)type {
return [MyClass getSpotType:type withPredicate:@"NOT (type = %@)" andMessage:@"[Spot spotWithType] -> %@"];
}