Saya menulis singleton yang memecahkan masalah beberapa koneksi dengan menyimpan penghitung dari apa yang terjadi (untuk menghindari penghapusan status ketika koneksi kembali tetapi yang lain masih aktif):
File header:
#import <Foundation/Foundation.h>
@interface RMActivityIndicator : NSObject
-(void)increaseActivity;
-(void)decreaseActivity;
-(void)noActivity;
+(RMActivityIndicator *)sharedManager;
@end
dan implementasi:
#import "RMActivityIndicator.h"
@interface RMActivityIndicator ()
@property(nonatomic,assign) unsigned int activityCounter;
@end
@implementation RMActivityIndicator
- (id)init
{
self = [super init];
if (self) {
self.activityCounter = 0;
}
return self;
}
-(void)increaseActivity{
@synchronized(self) {
self.activityCounter++;
}
[self updateActivity];
}
-(void)decreaseActivity{
@synchronized(self) {
if (self.activityCounter>0) self.activityCounter--;
}
[self updateActivity];
}
-(void)noActivity{
self.activityCounter = 0;
[self updateActivity];
}
-(void)updateActivity{
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = (self.activityCounter>0);
}
#pragma mark -
#pragma mark Singleton instance
+(RMActivityIndicator *)sharedManager {
static dispatch_once_t pred;
static RMActivityIndicator *shared = nil;
dispatch_once(&pred, ^{
shared = [[RMActivityIndicator alloc] init];
});
return shared;
}
@end
Contoh:
[[RMActivityIndicator sharedManager]increaseActivity];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:self.networkReceiveProcessQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
[[RMActivityIndicator sharedManager]decreaseActivity];
}