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() , 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 a ternary operator in Objective-C? In other languages, such as C #, the above three-dimensional operator would work correctly.

+4
source share
2 answers

I guess this is the order of operations. You tried:

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

(notification added by parens)

+10
source

@cesarislaw is probably right about the order of operations.

However, the code will be more readable if you do something similar instead (and if you really insist on using the ternary operator;)):

 NSDictionary * templates = (NSDictionary *) (self.inSearchMode ? self.filteredTemplates : self.templates); categorize = [[templates objectAtIndex:indexPath.row] objectForKey:@"categorize"]; 
+8
source

Source: https://habr.com/ru/post/1392561/


All Articles