Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single line if statement Objective-c

Tags:

objective-c

How would one go about writing a one line if statement in objective-c? Is there a proper style for this?

I know of the ternary operator used for assignment (int a = condition ? b : c) but say I wanted to call a method is if(condition){ [self methodCall]; } the recommended way of dealing with this in one line?

In addition are there any objc style guides out there? (Think comparable to this ruby style guide) Coming back to a language after a while of not touching it makes me want to rethink how I style my code.

like image 421
erran Avatar asked Nov 05 '12 23:11

erran


3 Answers

Ternary if statement (if - else)

condition ? [self methodcall] : [self otherMethodCAll];

Single method call

if (condition) [self methodcall];
like image 89
flavian Avatar answered Nov 11 '22 00:11

flavian


The single-line ruby-style if and unless statements do not have an equivalent in Objective-C. You can either stick with blocks, or just call the method on the same line:

if (condition) {
    [self method];
}

or

if (condition)
    [self method];

or

if (condition) [self method];
like image 37
mopsled Avatar answered Nov 11 '22 01:11

mopsled


You don't need brackets...

if(condition) [self methodCall];

That's as succinct as it gets.

like image 36
Michael Frederick Avatar answered Nov 11 '22 01:11

Michael Frederick