문제

So I have a method A which basically checks to see what the current state of UISwitches are and then alerts the user via a text-SMS service API. However; since it is constantly checking the state of the pins I do not want it to send the text 50000 times (spamming the SMS service); the final FOR loop within this method is the one that is checking to see if it should check the user; however with it's current state it constantly spams whenever the app is running.

Thanks if you need more clarification please ask.

Method A:

- (void)setInput:(NCDigitalInput *)input
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *baseString;
        uint8_t value = input.value;
        self.inputLabel.text = [NSString stringWithFormat:@"0x%0.2X",value];
        for (UISwitch *temp in switchArrayIn)
        {
            temp.on = (value & 1);
            value >>= 1;
        }
        for(int i = 0; i<switchArrayIn.count; i++){
            if(![defaults boolForKey:[NSString stringWithFormat:@"digitalInput%dRecentlyAlerted",i]] && ([[switchArrayIn objectAtIndex:i] isOn]) && ([defaults boolForKey:[NSString stringWithFormat:@"digitalInput%dBool",i]]) && ([defaults boolForKey:[NSString stringWithFormat:@"digitalInputAlertOn%dBool",i]])){
                [defaults setBool:TRUE forKey:@"digitalInput%dRecentlyAlerted"];
                baseString = [defaults objectForKey:@"digitalInput%d"];
                NSString *stringSMS = [baseString stringByAppendingString:@" has turned on"];
                [self digitalSMSCheck:i :stringSMS];
            }
            if(![defaults boolForKey:[NSString stringWithFormat:@"digitalInput%dRecentlyAlerted",i]] && !([[switchArrayIn objectAtIndex:i] isOn]) && ([defaults boolForKey:[NSString stringWithFormat:@"digitalInput%dBool",i]]) && ([defaults boolForKey:[NSString stringWithFormat:@"digitalInputAlertOff%dBool",i]])){
                [defaults setBool:TRUE forKey:@"digitalInput%dRecentlyAlerted"];
                baseString = [defaults objectForKey:@"digitalInput%d"];
                NSString *stringSMS = [baseString stringByAppendingString:@" has turned off"];

                [self digitalSMSCheck:i :stringSMS];
            }
        }}
도움이 되었습니까?

해결책

Change your design. Polling is bad, and not necessary.

Attach IBActions to each switch.

Make the switch's action methods set properties. If you have a lot of switches you can put tags on each switch and have a single method that handles all of them.

Then you can either create custom setters on your properties, or use key-value observing to watch for changes in the host properties. Take a look at the "Introduction to Key-Value Observing Programming Guide" in the Xcode docs for a description of how this works.

Which approach is better depends on the details of your application, plus your personal taste. KVC is a little slower than other methods, but it works well.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top