如何在iPhone上控制网络活动指示器

Che*_*rel 4 iphone networking cocoa-touch

我知道,为了显示/隐藏状态栏上的悸动,我可以使用

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
Run Code Online (Sandbox Code Playgroud)

但我的程序发送来自许多线程的comm请求,我需要一个位置来控制是否应该显示或隐藏throbber.

我想到了一个集中式的类,每个comm请求都会注册,这个类会知道一个或多个请求当前是否正在传输字节,并且会打开throbber,否则 - 关闭.

这是要走的路吗?为什么Apple没有在网络发生时自动出现问题

Ski*_*kie 7

尝试使用这样的东西:

static NSInteger __LoadingObjectsCount = 0;

@interface NSObject(LoadingObjects)

+ (void)startLoad;
+ (void)stopLoad;
+ (void)updateLoadCountWithDelta:(NSInteger)countDelta;

@end

@implementation NSObject(LoadingObjects)

+ (void)startLoad {
    [self updateLoadCountWithDelta:1];
}

+ (void)stopLoad {
    [self updateLoadCountWithDelta:-1];
}

+ (void)updateLoadCountWithDelta:(NSInteger)countDelta {
    @synchronized(self) {
        __LoadingObjectsCount += countDelta;
        __LoadingObjectsCount = (__LoadingObjectsCount < 0) ? 0 : __LoadingObjectsCount ;

        [UIApplication sharedApplication].networkActivityIndicatorVisible = __LoadingObjectsCount > 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:使其线程安全