[英]What are the limits of using a ternary operator in 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#中,上述三元语句可以正常工作。
我的猜测是这是一个操作顺序问题。 你有没有尝试过:
[(self.inSearchMode?self.templates:self.filteredTemplates) objectAtIndex:indexPath.row]
(通知添加了parens)
@cesarislaw可能是关于操作顺序的。
但是,如果您执行类似的操作,代码将更具可读性(如果您确实坚持使用三元运算符;)):
NSDictionary * templates = (NSDictionary *) (self.inSearchMode ? self.filteredTemplates : self.templates);
categorize = [[templates objectAtIndex:indexPath.row] objectForKey:@"categorize"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.