如何检查字符串是否更改

时间:2014-11-15 17:57:59

标签: ios objective-c

我是iOS编程的新手,但我需要它来测试原型。 我收到了蓝牙的值,当物理原型按下按钮时,它会发生变化。

在我的应用程序中,按下按钮时必须执行操作,因此我需要知道值何时更改。

我已经尝试了所有我能想到的东西并且到处寻找但没有找到解决方案。 这是我目前的代码:

-(void)bean:(PTDBean *)bean didUpdateScratchNumber:(NSNumber *)number withValue:(NSData *)data{
int value = *(int*)([data bytes]);
NSString *lastvalue = nil;
NSString *newValue = [NSString stringWithFormat:@"%d", value];
    NSLog(@"ScratchWaarde: %d", value);
if ([newValue isEqualToString:lastvalue]) {
    NSLog(@"Last Value: %@", lastvalue);
    }else{
        NSLog(@"Pushed");
        lastvalue = newValue;
    }
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

你的代码毫无意义。你在说:

NSString *lastvalue = nil;
NSString *newValue = // ...
if ([newValue isEqualToString:lastvalue]) {

在任何情况下,newValue 都不等于lastValue,因为lastValue保证为零,因为这是您设置它的值在第一行(和newValue,因为你将它设置为实际的NSString,保证为零)。

所以,虽然我不清楚你究竟想要完成什么,但显然不是这样。编程问题并不是简单的逻辑思维问题。该程序只能做你告诉它做的事情,而你告诉它要做的事情是愚蠢的。

(很可能你不理解的是lastvalue纯粹是本地方法的本地化,所以每次调用方法时它都是新的。如果你想要 persistent { {1}},您需要属性为全局属性,而不是局部变量。)

答案 1 :(得分:0)

是的,看起来OP期望lastValue在对象上保持状态,所以......

// in this class's interface
@property(strong,nonatomic) NSString *lastValue;

-(void)bean:(PTDBean *)bean didUpdateScratchNumber:(NSNumber *)number withValue:(NSData *)data{

    // it looks like the OP is trying to get a string from the data, so...
    NSString *newValue = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"ScratchWaarde: %d", value);
    if ([newValue isEqualToString:self.lastvalue]) {
        NSLog(@"Last Value: %@", self.lastvalue);
    } else {
        NSLog(@"Pushed");
        self.lastvalue = newValue;
    }
}