Reputation: 1972
I have some complex nested if else logic in a login and join method. If something goes wrong such as wrong password, no Internet and so forth, I fire an alert. In most cases, the only option is to click OK.
Since alerts don't stop code from executing, I try to put these alerts at the dead end of the conditional so that no more code is executed. However, given the complexity of the nested logic, to be on the safe side, I'd like to immediately end the method. My understanding is break only works in loops or switch statements.
Can a Return; statement safely be placed anywhere in a method in order to exit the method? I could not find this in Apple docs.
if ([hasInternet isEqual:@0]) {
[self fireAlertNoInternet];
return;
}
Thanks for any clarification.
Upvotes: 0
Views: 944
Reputation: 125037
Can a Return; statement safely be placed anywhere in a method in order to exit the method? I could not find this in Apple docs.
Yes, you can safely return from anywhere inside a method. A return statement in the body of a conditional or a loop isn't a problem, for example. That said, you do need to be careful to clean up after yourself before returning. This isn't as much of a concern under ARC as it was with manual memory management, but if you've allocated memory with malloc()
you might need to free it or make sure that something outside the method has a reference to that new block. If you've obtained any locks, you probably need to release them. Basically, any resources that your method has obtained should be released or disposed before you return early.
You also need to be careful to return a value of appropriate type if the method or function is declared to return something other than void
.
I could not find this in Apple docs.
That's because the behavior of return
is inherited from C and C++ — it's not specific to Apple or Objective-C.
Upvotes: 2
Reputation: 100541
Sure it can , return
is designated to exit function execution either with a returned value or not ( void ) depending on the needed case
Upvotes: 4