修复我的networking活动指标

我的networking活动指标存在问题,有时会在不应该显示的情况下继续显示。

我写了我自己的经理,并换了一个使用这样的NSAssert语句…

 - (void)setNetworkActivityIndicatorVisible:(BOOL)setVisible { static NSInteger NumberOfCallsToSetVisible = 0; if (setVisible) NumberOfCallsToSetVisible++; else NumberOfCallsToSetVisible--; // The assertion helps to find programmer errors in activity indicator management. // Since a negative NumberOfCallsToSetVisible is not a fatal error, // it should probably be removed from production code. NSAssert(NumberOfCallsToSetVisible >= 0, @"Network Activity Indicator was asked to hide more often than shown"); // Display the indicator as long as our static counter is > 0. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:(NumberOfCallsToSetVisible > 0)]; } 

我发现它,并立即指出,我使用这个function出了问题。

我所有的networking活动都是通过一个由单例类pipe理的单个NSOperationQueue来运行的。 每个操作都是NSOperation的子类(实际上是TemplateOperation的一个子类,它是NSOperation的子类)。

无论如何,所有的下载和上传工作正常,我做他们都是这样的…

 - (void)sendRequest:(NSURLRequest *)request { NSError *error = nil; NSURLResponse *response = nil; [[NetworkManager sharedInstance] setNetworkActivityIndicatorVisible:YES]; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; [[NetworkManager sharedInstance] setNetworkActivityIndicatorVisible:NO]; // other stuff... [self processData:data]; } 

重要的行是在我同步发送NSURLConnection之前和之后。

在我发送请求之前,我将networking活动指示器设置为可见(使用我的pipe理员类),然后立即将其设置为不可见。

除了NSAssert已经指出,这是不正确的地方。

难道是从多个线程运行这个函数可能会导致一个问题? 我怎么能解决这个问题?

整数递增或递减是不是线程安全的(据我所知),所以如果两个线程“同时”调用你的方法,计数可能无法正确更新。

一种解决scheme是将一些同步指令(如@synchronized )添加到您的方法。 或者你使用primefaces增量/减量函数:

 #include <libkern/OSAtomic.h> - (void)setNetworkActivityIndicatorVisible:(BOOL)setVisible { static volatile int32_t NumberOfCallsToSetVisible = 0; int32_t newValue = OSAtomicAdd32((setVisible ? +1 : -1), &NumberOfCallsToSetVisible); NSAssert(newValue >= 0, @"Network Activity Indicator was asked to hide more often than shown"); [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:(newValue > 0)]; }