我正在制作一个显示动画 UIImageView 的应用程序,作为指示应用程序繁忙的自定义方式。我正在使用 NSOperationQueue 进行文件上传,并且我希望 UIImageView 在队列中有内容时显示。当队列中的每个操作完成时,我想删除 UIImageView。
我认为这很容易做到,但过去一个小时我一直被困住。显示 UIImageView 真的很容易,但我似乎无法删除它。这可能是我忽略的非常简单的事情。这是我的代码。谢谢!:)
- (void)viewDidLoad {
//set up the uiimageview
self.spinnerView = [[UIImageView alloc] initWithFrame:CGRectMake([[UIScreen mainScreen] bounds].size.width-44,0,44,44)];
self.spinnerView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"0.gif"],
[UIImage imageNamed:@"1.gif"],
[UIImage imageNamed:@"2.gif"],
[UIImage imageNamed:@"3.gif"],
[UIImage imageNamed:@"4.gif"], nil];
self.spinnerView.animationDuration = 0.5f;
self.spinnerView.tag = 998;
self.spinnerView.animationRepeatCount = 0;
[self.view addSubview: self.spinnerView];
//set up the queue
self.uploadQueue = [[NSOperationQueue alloc] init];
[self.uploadQueue setMaxConcurrentOperationCount:1];
//set up observer for the queue
[self.uploadQueue addObserver:self forKeyPath:@"operationCount" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)newUpload:(NSData*)data {
[self.spinnerView startAnimating];
//....
//request is a NSURLRequest that's set up in this method
[NSURLConnection sendAsynchronousRequest:request queue:self.uploadQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
}];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context
{
if (object == self.uploadQueue && [keyPath isEqualToString:@"operationCount"]) {
if (self.uploadQueue.operationCount == 0) {
[self.spinnerView stopAnimating];
}
}
else {
[super observeValueForKeyPath:keyPath ofObject:object
change:change context:context];
}
我这样做正确吗?有更好的方法吗?我已经在这里停留了一段时间,并且开始认为可能不是 UIImageView 搞砸了,而是我将 NSURLRequests 添加到 NSOperationQueue 的方式。
再次感谢!