objective-c – 比较Objective C(Xcode)中的两个字符串时如何使
发布时间:2020-12-14 18:59:34 所属栏目:百科 来源:网络整理
导读:我想在一周的每一天显示一个不同的网站.我创建了一个NSString,它使用NSDateFormatter只包含一周中的当前日期.然后,我为一周中的每一天创建了额外的字符串.我在“IF”语句中比较两者……所以如果字符串(天)相等,它将在if语句中执行该函数.如果没有,它会检查下
我想在一周的每一天显示一个不同的网站.我创建了一个NSString,它使用NSDateFormatter只包含一周中的当前日期.然后,我为一周中的每一天创建了额外的字符串.我在“IF”语句中比较两者……所以如果字符串(天)相等,它将在if语句中执行该函数.如果没有,它会检查下一个语句.现在它将适用于周一的第一个声明,但是当我在iPhone上更改日期以模拟一周中的其他日期时,它将无效.我的代码如下!
NSDateFormatter *dayofweekformatter = [[NSDateFormatter alloc] init]; [dayofweekformatter setDateFormat:@"cccc"]; NSString *DayOfWeek = [dayofweekformatter stringFromDate:[NSDate date]]; NSString *Monday = @"Monday"; NSString *Tuesday = @"Tuesday"; NSString *Wednesday = @"Wednesday"; NSString *Thursday = @"Thursday"; NSString *Friday = @"Friday"; NSString *Saturday = @"Saturday"; NSString *Sunday = @"Sunday"; if ([DayOfWeek isEqualToString:Monday]) { // Webview code NSString *urlAddress = @"http://www.google.com"; //Create a URL object. NSURL *url = [NSURL URLWithString:urlAddress]; //URL Requst Object NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; //Load the request in the UIWebView. [webview loadRequest:requestObj]; } else if (dateToday == Tuesday) { // Webview code NSString *urlAddress = @"http://www.cnn.com"; //Create a URL object. NSURL *url = [NSURL URLWithString:urlAddress]; //URL Requst Object NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; //Load the request in the UIWebView. [webview loadRequest:requestObj]; 解决方法
以下是更好的解决方案,使用工作日的索引来确定您的网址:
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:[NSDate date]]; NSInteger weekday = [components weekday]; NSString *urlString; switch(weekday){ case 1: // sunday urlString = @"http://google.com"; break; case 2: urlString = @"http://twitter.com"; break; case 3: urlString = @"http://facebook.com"; break; case 4: urlString = @"http://yahoo.com"; break; case 5: urlString = @"http://mashable.com"; break; case 6: urlString = @"http://bbc.co.uk"; break; case 7: // saturday urlString = @"https://stackoverflow.com"; break; default: urlString = @"http://google.com?q=weekday+is+never+this!"; break; } NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; //Load the request in the UIWebView. [webview loadRequest:requestObj]; 要按照您对评论的要求刷新支票,您可以这样做: 在您的应用程序委托文件中,将此行添加到applicationDidBecomeActive:方法中 - (void)applicationDidBecomeActive:(UIApplication *)application { [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDateCheck" object:nil]; } 在您的班级中,您正在进行日期检查,在init方法中添加此行以收听应用程序退出后台时发送的任何刷新通知: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMethod) name:@"refreshDateCheck" object:nil]; 最后将日期检查代码移到此方法,该方法在收到通知时调用: -(void)myMethod{ /* Your other code goes in here */ } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |