ItsASecret
ItsASecret

Reputation: 2649

Don't understand this syntax in Objective-C

In this answer : https://stackoverflow.com/a/4481896/1486928

there is a line like this :

 UITableView *tableView = controller == self.fetchedResultsController ? self.tableView : self.searchDisplayController.searchResultsTableView;

It's the first time I see all these symbols in the same line :/ (I'm a beginner).

Upvotes: 2

Views: 214

Answers (5)

LuckyLuke
LuckyLuke

Reputation: 49047

This shows you the ternary operator.

Upvotes: 1

Swayam
Swayam

Reputation: 16354

It means that if controller is equal to self.fetchedResultsController, then

set tableView = self.tableView, otherwise

set tableView = self.searchDisplayController.searchResultsTableView

You could represent it as

UITableView *tableView;
 if (controller == self.fetchedResultsController)
     tableview = self.tableView;
 else
     tableview = self.searchDisplayController.searchResultsTableView;

Upvotes: 2

Tom Naessens
Tom Naessens

Reputation: 1837

something ? foo : bar is just a shorter version of

if(something) {
   foo
} else {
   bar 
}

It is called the ternary operator.

So your piece of code becomes:

UITableView *tableView;
if(controller == self.fetchedResultsController) {
    tableView = self.tableView;
} else {
    tableView = self.searchDisplayController.searchResultsTableView;
}

Upvotes: 4

user529758
user529758

Reputation:

This is the conditional operator. What it does is basically it returns one of two values based on its condition:

SomeType variable = condition ? valueIfTrue : valueIfFalse;

This can be interpreted as

SomeType variable;
if (condition) {
    variable = valueIfTrue;
} else {
    variable = valueIfFalse;
}

Here the condition is

controller == self.fetchedResultsController

so of the view controller is equal to self.fetchedResultsController, the tableView variable will be assigned to self.tableView, else it'll be assigned to self.searchDisplayController.searchResultsTableView

Upvotes: 4

nneonneo
nneonneo

Reputation: 179382

This is an example of the ternary operator.

Written out longhand:

 UITableView *tableView;
 if (controller == self.fetchedResultsController)
     tableview = self.tableView;
 else
     tableview = self.searchDisplayController.searchResultsTableView;

Upvotes: 1

Related Questions