【问题标题】:Access to NSUInteger property访问 NSUInteger 属性
【发布时间】:2013-07-05 20:48:39
【问题描述】:

在我的代码中访问 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];

你有什么建议或提示我在我的代码中做错了什么?

【问题讨论】:

  • 你分配/初始化更新数组了吗?
  • 是的,我做到了。我将这行代码从我的示例中排除在外。
  • 你确定你的视图在 updatesArray 被分配之前加载了吗?
  • 是的,我这样做:MyController *myVC = [self.storyboard instantiateViewControllerWithIdentifier:@"MyController"]; myVC.updatesArray = 更新数组; [self presentViewController:myVC 动画:YES 完成:nil];

标签: objective-c multithreading nsnotificationcenter nsoperationqueue nsinvocationoperation


【解决方案1】:

好的,我找到了问题的原因。通过从队列启动的操作访问同一变量来锁定应用程序。当我更改代码的逻辑时,一切都开始正常工作。

【讨论】:

    猜你喜欢
    • 2015-11-03
    • 1970-01-01
    • 2017-03-16
    • 2013-12-23
    • 2013-07-11
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多