2011-11-23 64 views
0

这里我想比较2个URL的主机。即使这些主机是相同的,它不会回应为什么!URL主机比较

代码:

NSURL *url=[NSURL URLWithString:@"http://www.facebook.com/"?ref=logo" ]; 
    NSURL *domain=[ NSURL URLWithString:@"http://www.facebook.com" ]; 

    if ([url host]==[domain host]) { 

     NSLog(@"hosts are matched"); 
    }else { 
     NSLog(@"hosts are not matched!"); 
    } 

回答

3

您需要使用isEqualToString:

NSURL *url=[NSURL URLWithString:@"http://www.facebook.com/?ref=logo" ]; 
NSURL *domain=[ NSURL URLWithString:@"http://www.facebook.com" ]; 

if ([[url host] isEqualToString: [domain host]]) { 
    NSLog(@"hosts are matched"); 
}else { 
    NSLog(@"hosts are not matched!"); 
} 

结果

2011-11-23 11:55:06.182 TestApp [14404:207]主机是匹配

+1

的确如此。执行==比较将检查这两个对象在计算机的内存空间中是否物理上相同。在这种情况下,字符串在语义上是相同的,但存储在不同的地方,因此==将返回false。 “aString isEqualToString:anotherString]将会进行基于字符的比较,这就是你要找的。” – Warkst

+0

@Warkst,谢谢,我将解释这一点,但你会更快;) – beryllium