0

I'm doing some networking stuff in one of my methods and I would like the method to return NO and stop executing early if one of the internal calls returns an error, a bit like break for loops. Is this possible?

IMO it would produce cleaner code rather than using a BOOL flag and having "should I continue executing this code?" if statements all over the place; and then finally at the end of the method returning YES or NO based on the flag.

Any thoughts are much appreciated!

lmirosevic
  • 15,787
  • 13
  • 70
  • 116

1 Answers1

1

Yes, you can.

return NO;

Return statements are acceptable everywhere in functions and methods. I personally prefer to make use of early returns because it usually leads to less nesting (and thus code easier to understand).

There are several similar questions around here:

Community
  • 1
  • 1
zneak
  • 134,922
  • 42
  • 253
  • 328
  • Agreed on the early return. One caveat; if you are using retain-release (not Garbage Collection), be careful to release any retained variables prior to the early return. – bbum Sep 11 '10 at 16:01
  • Thanks for the reply! That's exactly what I did in my code but the method still execute to the end... or so I thought because I saw a log message in the terminal that I thought was being printed from within the method. It turned out I was printing the message not from within the method but back from where I was calling the method. Silly mistake. I looked at the other threads but because of my coding error assumed it would be different in ObjC. Thanks again! – lmirosevic Sep 11 '10 at 16:19