views:

75

answers:

3

Writing some Objective-C in one method, I call +alloc, then -init to set up an object.

object = [[MyClass alloc] init];
[object useFor:whatever];

The next few lines of code use the newly created object. If the aforementioned -init takes too long, I’m sure the program won’t “wait” before starting to use the new object, will it? If not, is there a quick way to assure the -init is completed?

I sometimes see programmers who write something along the lines of

if(object = [[MyClass alloc] init]) {
    [object useFor:whatever];
}

Is this what I should go for?

+3  A: 

commands are executed in sequential order and not paralell

(dude, learn some basics ;)

Tomen
Heh, thanks. Though to be fair, basics literature in ObjC usually go "LOOK ITS A TEXT EDITOR WITHOUT CODE OMG" and fail the theory.
Not Rick Astley
+9  A: 

When you call init the program will not go on to the next line until the init method returns.

The second form is a test. First the if statement calls the init method. If a valid object is returned then the test is true and then the next statement is executed. This is why you see init methods that return self when they are successful and nil when there is a problem; so that tests like these can be run to be sure that the object has been successfully initialised.

Abizern
+2  A: 

As a rule, statements in C and Objective-C functions (and methods) are executed in sequence, in the order you write them. If you write one thing before another in a function, the first one must complete execution before the next one can execute.

The compiler may reorder statements if it believes that doing so will not change the behavior of the program (which it can predict very well in situations that don't involve concurrency), but this is an optimization. The C standard treats statements as being sequential, but allows compilers to implement this any way they like as long as the behavior of the actual program is the same as if the statements had been executed in the sequence in which they were written.

All this is a long way of saying: Your init method will complete before the calling method can resume execution.

Chuck
Thanks, that’s very helpful. I figured method calls (or message sends) behaved differently, but now I realise this is not the case.
Not Rick Astley