我在代码中访问NSUInteger属性时遇到了一些问题,如下所示:
MyController.h
@interface MyController : UIViewController
@property (retain, nonatomic) NSArray *updatesArray;
@property (nonatomic) NSUInteger madeUpdatesCounter;
@property (nonatomic) NSUInteger allUpdatesCounter;
@end
MyController.m
@implementation MyController
@synthesize updatesArray;
@synthesize madeUpdatesCounter;
@synthesize allUpdatesCounter;
- (void)viewDidLoad
{
....
madeUpdatesCounter = 0;
allUpdatesCounter = [updatesArray count];
....
// Register for progress notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(makeProgressChange)
name:@"MadeOneUpdateNotification"
object:nil];
}
- (void)makeProgressChange
{
madeUpdatesCounter++;
NSLog(@"Update progress: %d/%d", madeUpdatesCounter, allUpdatesCounter);
}
@end
我通过添加到NSOperationQueue,将我的更新作为NSInvocationOperation处理。在一个更新操作的最后,我发送通知:
[[NSNotificationCenter defaultCenter] postNotificationName:@"MadeOneUpdateNotification" object:nil];
在执行了上面的代码后,接收通知只执行一次,在日志中我看到了这样的情况:
更新进度:1/3
当我换线时:
allUpdatesCounter = [updatesArray count];
至
allUpdatesCounter = 3;
然后一切正常,我在日志中看到:更新进度:1/3更新进度:2/3更新进度:3/3
变量updatedArray在加载视图之前进行初始化。是这样做的:
MyController *doUpdatesVC = [self.storyboard instantiateViewControllerWithIdentifier:@"MyController"];
doUpdatesVC.updatesArray = updatesArray;
[self presentViewController:doUpdatesVC animated:YES completion:nil];
你有什么建议或暗示我在代码中做错了什么吗?
好吧,我找到了问题的原因。通过从队列启动的操作访问同一变量而锁定的应用程序。当我更改代码的逻辑时,一切都开始正常工作。