在Objective-C中使用三元运算符有什么限制?

Chr*_*isP 4 objective-c ternary-operator ios

以下Objective-C语句无法正常工作.

cell.templateTitle.text=[(NSDictionary*) [self.inSearchMode?self.templates:self.filteredTemplates objectAtIndex:indexPath.row] objectForKey:@"title"];
Run Code Online (Sandbox Code Playgroud)

但是,如果我将其拆分为一个if()声明,它可以正常工作.

if(self.inSearchMode){
  categorize=[(NSDictionary*)[self.filteredTemplates objectAtIndex:indexPath.row] objectForKey:@"categorize"];
} else {
  categorize=[(NSDictionary*)[self.templates objectAtIndex:indexPath.row] objectForKey:@"categorize"]; 
}
Run Code Online (Sandbox Code Playgroud)

在Objective-C中使用三元运算符有什么限制?在其他语言如C#中,上述三元语句可以正常工作.

ces*_*law 10

我的猜测是这是一个操作顺序问题.你有没有尝试过:

[(self.inSearchMode?self.templates:self.filteredTemplates) objectAtIndex:indexPath.row]
Run Code Online (Sandbox Code Playgroud)

(通知添加了parens)


mac*_*die 8

@cesarislaw可能是关于操作顺序的.

但是,如果您执行类似的操作,代码将更具可读性(如果您确实坚持使用三元运算符;)):

NSDictionary * templates = (NSDictionary *) (self.inSearchMode ? self.filteredTemplates : self.templates);

categorize = [[templates objectAtIndex:indexPath.row] objectForKey:@"categorize"];
Run Code Online (Sandbox Code Playgroud)