简体   繁体   中英

What are the limits of using a ternary operator in Objective-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.

My guess is that it's an order of operations issue. Have you tried:

[(self.inSearchMode?self.templates:self.filteredTemplates) objectAtIndex:indexPath.row]

(notice added parens)

@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 ;) ):

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

categorize = [[templates objectAtIndex:indexPath.row] objectForKey:@"categorize"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM