多次调用函数时,将项添加到数组一次?

时间:2017-06-14 13:31:53

标签: objective-c arrays callback delegates

如果频道高于阈值,我想将频道添加到频道数组中,此功能是提供频道级别的委托回调。

此fucn不断用于提供级别数据,但是在初始化时我想将高于阈值的通道添加到数组中。然而,我不希望它再次添加它们,只需要符合条件的每个通道的1个实例。

我想使用此代码并检查我收到数据的频道是否已经在channelArray中,如果不是,则添加它,如果是,则跳过它...但是它没有调用/工作。< / p>

任何人都可以帮我解决这个问题吗?问题是每个通道在每次移动时调用此函数,所以我需要它才能运行代码一次添加到数组。

- (void)cdcControlDidReceiveBusSend:(NSInteger)channel withValue:(float)value forBus:(NSInteger)bus onModule:(NSInteger)module {
    NSNumber *recievingChannel = [NSNumber numberWithInteger:channel];
    NSLog(@"RECIEVED SEND DATA FOR CHAN:%ld VALUE:%f FORBUS:%ld", (long)channel, value, (long)bus);
    if (value != -80.000000) {
        NSLog(@"CHANNEL:%ld FADER IS UP ATTEMPTING TO ADD TO FOCUS ARRAY", (long)channel);

        for (NSNumber *arrayChannel in self.focusChannels) {
            if (recievingChannel == arrayChannel) {
                NSLog(@"ALREADY SAVED THIS CHANNEL...SKIPPING");
            } else {
                NSLog(@"ADDING CHANNEL %ld", (long)channel);
                [self.focusChannels addObject:[NSNumber numberWithInteger:channel]]; // add the channel number to the array of channel numbers if the fader is up
                NSLog(@"FOCUS ARRAY NOW CONTAINS %lu CHANNELS", (unsigned long)self.focusChannels.count);
            }
        }

    } else {
        NSLog(@"CHANNEL:%ld FADER IS DOWN NOT IN MIXFOCUS ARRAY", (long)channel);
    }
}

1 个答案:

答案 0 :(得分:0)

您无法使用==运算符来比较NSNumber的值。为了做正确的事情你需要使用比较法,比如isEqueal

if ([recievingChannel isEqual:arrayChannel]) {
    //...
}

或直接比较值

if (recievingChannel.integerValue == arrayChannel.integerValue){
    //...
}

无论如何,可以使用-[NSArray containsObject:]

解决此任务
- (void)cdcControlDidReceiveBusSend:(NSInteger)channel withValue:(float)value forBus:(NSInteger)bus onModule:(NSInteger)module {
    if (value != -80.000000) {
        if ([self.focusChannels containsObject:@(channel)] == NO) {
            [self.focusChannels addObject:@(channel)];
        }
    }
}