我正在尝试实现此按钮操作,但if语句未评估为true。我有一种情况,即“学校”字典中的值不会总是存储网站。出于这个原因,我想检查,但我要检查什么。如果没有值时没有存储“nil”,那么是什么?
-(IBAction) btnVisitWebsite_clicked :(id)sender {
if([School objectForKey:WEBSITE_KEY] == nil){
UIAlertView *NoWebsite = [[UIAlertView alloc]initWithTitle: @"No Website"
message:@"The selected school has not listed a website"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
NoWebsite.tag = 15;
[NoWebsite show];
[NoWebsite release];
NoWebsite = nil;
}
else{
NSMutableString *WebsiteVisit = [[NSMutableString alloc] initWithString: @"http://"];
[WebsiteVisit appendString:[School objectForKey:WEBSITE_KEY]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: WebsiteVisit]];
[WebsiteVisit release];
}
}
答案 0 :(得分:3)
如果网站可能是空字符串,则应使用以下内容:
if(![School objectForKey:WEBSITE_KEY]
|| ([[School objectForKey:WEBSITE_KEY] isKindOfClass:[NSString class]] && [(NSString*)[School objectForKey:WEBSITE_KEY] length]==0)){
// no website
} else { /* has website*/ }
答案 1 :(得分:1)
NSDictionary不能包含nil。如果密钥存在,则必须包含对象。如果没有为特定键定义对象,objectForKey:
方法将返回nil
。但是,您可以将[NSNull null]
存储为字典或数组中的空占位符。所以你可以检查一下,这完全取决于字典的填充方式。
[School objectForKey:WEBSITE_KEY] == nil || [School objectForKey:WEBSITE_KEY] == [NSNull null]
同时确保您不会将@“”与零值或无值混淆。如果它不是nil而不是[NSNull null]那么最好记录它,也许看一下存储的对象:
NSLog(@"Description: %@", [School objectForKey:WEBSITE_KEY]);
NSLog(@"Class: %@", [[School objectForKey:WEBSITE_KEY] class]);
如果类返回NSString或NSCFString,则它看起来像包含空字符串。你可以检查哪个。以下是完整的声明:
id schoolWebsite = School objectForKey:WEBSITE_KEY];
if (schoolWebsite && schoolWebsite != [NSNull null] && [schoolWebsite isKindOfClass:[NSString class]] && [schoolWebsite length] > 0)) {
// There is definitely a non-empty string for that key!
} else {
// Not valid
}
这将很好用,因为您可能不确定字典中存储的内容,因为其他人将填充它。你永远不能太小心!
答案 2 :(得分:1)
您是否尝试使用NSLog
打印密钥对象?
NSLog(@"School[WEBSITE_KEY]=<%@>", [School objectForKey:WEBSITE_KEY]);
也许这不是零?
答案 3 :(得分:1)
通过检查是否有条目
来查看所请求的学校是否在NSDictionary中BOOL containsKey = [[School allKeys] containsObject:WEBSITE_KEY];
如果没有学校网站,则不应该有WEBSITE_KEY的目录条目。