[英]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.