if 语句使用 == 检查 NSString 相等性
我正在一些 Objective-c 代码中进行服务器调用。如果它返回为 @"yes"
,它将执行一个操作。由于某种原因,永远不会到达 // DO ACTION HERE
部分。
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSString *returnStringResults = returnString;
NSString *yesText = @"yes";
if (returnStringResults == yesText) {
testLabel.text = @"Success";
// DO ACTION HERE
}
I am making a server call in some Objective-c code. If it returns as a @"yes"
, it will do an action. For some reason, the // DO ACTION HERE
part is never reached.
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSString *returnStringResults = returnString;
NSString *yesText = @"yes";
if (returnStringResults == yesText) {
testLabel.text = @"Success";
// DO ACTION HERE
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:正如 bbum 指出的那样,
NSString *returnStringResults = returnString;
不执行任何操作。所以真的,删除该行并使用
Edit: As bbum pointed out,
NSString *returnStringResults = returnString;
does nothing.So really, remove that line and use
您正在比较指针地址。此代码的工作方式
yesText
和returnStringResults
是指向不同 NSString 实例的指针,因此指针不相等。您必须使用 NSStringisEqualToString
方法进行比较。You're comparing pointer addresses. The way this code works
yesText
andreturnStringResults
are pointers to different NSString instances, thus the pointers are not equal. You've to use NSStringisEqualToString
method to compare.