当开关更改位置时,我使用NSNotification发送通知以开始更新地图上的注释。我的问题是我有8个开关,并且当用户更改几个开关的位置时,地图会多次更新。如何限制到仅一个通知?

- (IBAction)saveSwitch:(id)sender
{

    [[NSNotificationCenter defaultCenter] postNotificationName:@"MyAppSettingsChanged" object:self userInfo:nil];


    NSUserDefaults *defs1 = [NSUserDefaults standardUserDefaults];
    [defs1 setBool: blackSwitch.on forKey: @"blackKey"];

    NSUserDefaults *defs2 = [NSUserDefaults standardUserDefaults];
    [defs2 setBool: greenSwitch.on forKey: @"greenKey"];

    NSUserDefaults *defs3 = [NSUserDefaults standardUserDefaults];
    [defs3 setBool: purpleSwitch.on forKey: @"purpleKey"];

    NSUserDefaults *defs4 = [NSUserDefaults standardUserDefaults];
    [defs4 setBool: orangeSwitch.on forKey: @"orangeKey"];

    NSUserDefaults *defs5 = [NSUserDefaults standardUserDefaults];
    [defs5 setBool: blueSwitch.on forKey: @"blueKey"];

    NSUserDefaults *defs6 = [NSUserDefaults standardUserDefaults];
    [defs6 setBool: redSwitch.on forKey: @"redKey"];

    NSUserDefaults *defs7 = [NSUserDefaults standardUserDefaults];
    [defs7 setBool: darkblueSwitch.on forKey: @"darkblueKey"];

    NSUserDefaults *defs8 = [NSUserDefaults standardUserDefaults];
    [defs8 setBool: yellowSwitch.on forKey: @"yellowKey"];

    [[NSUserDefaults standardUserDefaults] synchronize];

}


在另一种观点

- (void)viewWillAppear:(BOOL)animated
{
     [super viewWillAppear:animated];

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppSettingsChanged:) name:@"MyAppSettingsChanged" object:nil];

}


更新注释

- (void) onAppSettingsChanged:(NSNotification *)notification {

    NSLog(@"Settings was changed");

    //Create the thread
    [NSThread detachNewThreadSelector:@selector(loadPList) toTarget:self withObject:nil];

}

最佳答案

您必须更新一些BOOL ean值以指示您当前未在处理更新,然后进行相应的操作。即

- (void) onAppSettingsChanged:(NSNotification *)notification {
    NSLog(@"Settings was changed");
    if (!myBoolToIndicateProcessing) {
      //Create the thread
      myBoolToIndicateProcessing = YES;
      [NSThread detachNewThreadSelector:@selector(loadPList) toTarget:self withObject:nil];
    }
}


然后,在重新加载完成后,将BOOL设置回NO。

关于ios - 有没有办法限制NSNotification?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10922628/

10-12 12:35