在 Objective-C 中使用三元运算符有哪些限制?
以下 Objective-C 语句无法正常工作。
cell.templateTitle.text=[(NSDictionary*) [self.inSearchMode?self.templates:self.filteredTemplates objectAtIndex:indexPath.row] objectForKey:@"title"];
但是,如果我将其拆分为 if()
语句,它就可以正常工作。
if(self.inSearchMode){
categorize=[(NSDictionary*)[self.filteredTemplates objectAtIndex:indexPath.row] objectForKey:@"categorize"];
} else {
categorize=[(NSDictionary*)[self.templates objectAtIndex:indexPath.row] objectForKey:@"categorize"];
}
在 Objective-C 中使用三元运算符有哪些限制?在其他语言(如 C#)中,上述三元语句可以正常工作。
The following Objective-C statement does not work correctly.
cell.templateTitle.text=[(NSDictionary*) [self.inSearchMode?self.templates:self.filteredTemplates objectAtIndex:indexPath.row] objectForKey:@"title"];
However, if I split it into an if()
statement it works fine.
if(self.inSearchMode){
categorize=[(NSDictionary*)[self.filteredTemplates objectAtIndex:indexPath.row] objectForKey:@"categorize"];
} else {
categorize=[(NSDictionary*)[self.templates objectAtIndex:indexPath.row] objectForKey:@"categorize"];
}
What are the limitations of using the ternary operator in Objective-C? In other languages like C# the above ternary statement would have worked correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的猜测是这是操作顺序问题。您尝试过吗:(
注意添加括号)
My guess is that it's an order of operations issue. Have you tried:
(notice added parens)
@cesarislaw 关于操作顺序的说法可能是正确的。
但是,如果您执行类似的操作(并且如果您确实坚持使用三元运算符 ;) ),则代码将更具可读性:
@cesarislaw is probably right about the order of operations.
However, the code will be more readable if you do something like this instead (and if you really insist on use of the ternary operator ;) ):