完成FetchRequest完成时的块/callback

我在名为ContentManager模型类中有一个FetchRequest 。 它获取了大量的数据,所以屏幕一直是空白的,直到完成。 在显示获取结果的ViewController中,我想显示一个加载指示器,所以我想在FetchRequest完成时得到一个callback,并将其传递给ViewController来停止加载指示器。 这可能吗?

以下是来自ContentManager类的FetchRequest

 - (NSArray*)recipesForMagazine { NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Recipe" inManagedObjectContext:managedObjectContext]; [request setEntity:entity]; NSString* path = [[NSBundle mainBundle] pathForResource:@"magazine_recipe_guids" ofType:@"plist"]; NSArray* recipeGuids = [NSArray arrayWithContentsOfFile:path]; NSPredicate* predicate = [NSPredicate predicateWithFormat:@"guid IN %@",recipeGuids]; [request setPredicate:predicate]; NSSortDescriptor* sort = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]; [request setSortDescriptors:[NSArray arrayWithObject:sort]]; [sort release]; NSError* error = nil; NSArray* fetchResults = [managedObjectContext executeFetchRequest:request error:&error]; [request release]; return fetchResults; } 

在这里我把它设置在ViewController

self.magazineRecipes = [[ContentManager defaultManager] recipesForMagazine];

我想设置这样的fetchrequest方法:

- (NSArray*)recipesForMagazine:(void (^)(BOOL success))block或什么的,所以在- (NSArray*)recipesForMagazine:(void (^)(BOOL success))block ,我可以这样称呼它

 self.magazineRecipes = [[CTContentManager defaultManager] recipesForMagazine:^(BOOL success) { if (success) { //stop activity indicator view } }]; 

我不知道我是否有正确的思维方式,感谢您的帮助!

我会让viewController成为ContentManager类的委托。 所以在ContentManager.h我会这样做:

  @protocol ContentManagerDelegate() -(void) didFetchResults:(NSArray *) results; -(void) didResultsFail: (NSError *) error; @end @interface ContentManager : <SuperClass Name> -(id) initWithDelegate: (id<ContentManagerDelegate>) delegate; @property (nonatomic, strong) id<ContentManagerDelegate> delegate; @end 

并在执行中:

  -(id) initWithDelegate: (id<ContentManagerDelegate>) delegate { self = [super init]; if(self) { _delegate = delegate; } return self; } 

并且在recipesForMagazine方法中,您可以使用委托[_delegate didFetchResults: fetchResults] ,如果需要,也可以实现一个将错误传递给委托的方法。 在你的ViewController.h执行@interface ViewController.h : UIViewController <ContentManagerDelegate> ,在实现中,你应该能够实现didFetchResults:方法,它会给你结果,在这个方法中,你可以停止animation指示器。