How can I make sure an object has finished initialising before using it?
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开发者_如何学Python 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?
When you call init
the program will not go on to the next line until the init
method returns. By the time you've reached the second line, the init method has completed. It may not have completed successfully, but it will have completed.
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 before continuing.
commands are executed in sequential order and not paralell
(dude, learn some basics ;)
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.
精彩评论