判断字符串是否相等 isEqualToString:

// if((btn.currentTitle == answerBtn.currentTitle) && btn.hidden == YES)
// 字符串相等比较 不要直接比,这样比的是指针,不是指针指向的数据
if([btn.currentTitle isEqualToString:answerBtn.currentTitle] && btn.hidden == YES)

 

 

 

 

NSString *strA = [NSString stringWithFormat:@"a"];

NSString *strB = [NSString stringWithFormat:@"b"];

if( strA == strB)

    NSLog(@"A is equal to B");

    else

    NSLog(@"A is not equal to B");

 

运行这段code, 在console 上的输出是: A is not equal to B

 

代码做些改动, 将 strA 与strB 设为相等。

NSString *strA = [NSString stringWithFormat:@"a"];

NSString *strB = [NSString stringWithFormat:@"a"];

if( strA == strB)

    NSLog(@"A is equal to B");

    else

    NSLog(@"A is not equal to B");

 

运行这段code ,在console上的输出仍然是 A is not equal to B 。

这是为什么呢 ?问题出在 字符串对比的语句上。

 

if ( strA == strB) // 这个strA, strB 是指针, 虽然字符串的内容是相同的, 但指向字符串的 指针肯定是不同的, 也不能相同啊。 (为了更好地理解字符串,需要弄清楚 指针的概念。 内存的分配。 )

 

    // 错误:if( strA == strB)

    // 正确: if ([strA isEqualToString:strB]) 

iOS SDK 本身 也提供了 字符串对比的方法: isEqualToString:

posted @ 2016-04-01 11:52  EricSun  阅读(1234)  评论(0编辑  收藏  举报