判断字符串是否相等 isEqualToString:

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

 

 

 

 

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 设为相等。 code

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 。orm

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

 

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

 

    // 错误:if( strA == strB)字符串

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

iOS SDK 自己 也提供了 字符串对比的方法: isEqualToString: it

相关文章
相关标签/搜索