【问题标题】:Strings which should be equal compare as not equal [duplicate]应该相等的字符串比较不相等[重复]
【发布时间】:2014-07-19 09:40:35
【问题描述】:

我想构建一个每天显示一个字符串的应用程序,但我不知道如何检测新的一天已经到来。

我尝试将字符串设置为initialString 记录您上次打开应用程序的日期,并将字符串设置为nowString 记录当前时间。如果initialString != nowString,它将在应用程序的UILabel 中显示一个新字符串,并将initialString 更新为与nowString 相同。如果它们相同,则不会发生任何事情。

这是我的代码;编译器说两个字符串即使它们是不一样的。

实现文件:

#import "QuoteViewController.h"
#import "Quotes.h"

@interface QuoteViewController ()

@end

@implementation QuoteViewController

@synthesize View1;
@synthesize View2;

//Will be used in the future.
//@synthesize View3;



- (void)viewDidLoad
{
    // Do any additional setup after loading the view, typically from a nib.
    [super viewDidLoad];

    [self addChildViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"View1"]];
    [self addChildViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"View2"]];

    self.quotes = [[Quotes alloc] init];

    self.now = [[NSDate alloc] init];
    self.initialString = @"1";

    [self timer];

}

#pragma mark - timer

- (void) timer {

    //This repasts the method checkDate every one second

    [NSTimer scheduledTimerWithTimeInterval:1.0f
                                     target:self
                                   selector:@selector(checkDate)
                                   userInfo:nil
                                    repeats:YES];

}

#pragma mark - checkDate

- (void) checkDate {

    //Date

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd"];

    NSString *nowString = [dateFormatter stringFromDate:self.now];

    NSLog(@"self.initialString is: %@", self.initialString);
    NSLog(@"now is: %@", nowString);


    //both Strings are the same but the compiler still says they're not the same and keep calling the method [showQuote]

    if (self.initialString != nowString) {
        self.initialString = nowString;
        [self showQuote];

        NSLog(@"AFTER THE METHOD THE STRING IS %@", self.initialString);
    }

    else { NSLog(@"IT'S THE SAME");}

}

#pragma mark - showQuote

- (void) showQuote {
    self.quoteLabel.text = [self.quotes randomQuote];
}

@end

我比较这些字符串有什么问题?

【问题讨论】:

  • 我对此进行了编辑并将其作为副本关闭,因为您的特定代码的问题与您获得日期更改通知的更大目标并没有特别相关。这篇文章真的是两个问题合二为一:“字符串比较有什么问题?”和“我怎样才能每天采取行动?”由于您已经收到第二个答案,欢迎您编辑您的问题以询问该问题,但代码将无关紧要,因此您应该将其删除。如果您进行了编辑,请给我留言,我将重新打开该问题。

标签: ios objective-c string cocoa-touch nsstring


【解决方案1】:

UIApplicationDelegate 的applicationSignificantTimeChange: 会在新的一天开始时通知您。

【讨论】:

  • 请记住,这有几个不同的原因,而不仅仅是在新的一天开始时。
猜你喜欢
  • 2015-01-05
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多