Using the GCC C Extension (Operator Expression) in Objective-C to Initialize

GNU C provides several language features not found in standard C. These extensions are available in C and Objective-C.

There is a GCC C extension (known as an expression expression ) that calls a sequence of statements surrounded by curly braces to return a value if they are also surrounded by parentheses:

self.searchBar = ({
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:({
        CGRect frame = self.tableView.frame;
        frame.size.height = 100.0f;
        frame;
    })];
    searchBar.delegate = self;
    searchBar;
});

In this design, parentheses span braces. The value of the last statement serves as the value of the whole construct, so we can use it to initialize and assign, among other things.

There are many advantages to initialization in this design:

  • clear and concise
  • initialization configuration information
  • smaller scale

, ? ?

+4

All Articles