I wonder if anyone could help me with a design/layout question. If you come to a point in your code where you want to stop execution and return an error how do you approach cleaning up? do you simply duplicate that code as I have done here, or is there another way?
if(fileContents == nil) {
NSLog(@"ReadError: %@", [fileError localizedDescription]);
[pool drain];
return 1;
} else {
NSLog(@"Succ开发者_开发问答ess : %@", fileContents);
}
// Clean up
[pool drain];
return 0;
}
// END
gary
For exactly your case it is easier to introduce variable named "result".
int result = 0;
if(fileContents == nil) {
NSLog(@"ReadError: %@", [fileError localizedDescription]);
result= 1;
} else {
NSLog(@"Success : %@", fileContents);
}
// Clean up
[pool drain];
return result;
}
// END
I use a similar approach to RocketSurgeon except that I use it as a running "everything is ok" flag. That way I can set ok
to false
at any point, skip any further code, but still have all the relevant cleanup (including frees in C, as shown) at the end.
bool ok = true;
type *someptr = 0;
if (ok)
{
if ((someptr = (type *)malloc(...)) == NULL)
{
// report error
ok = false;
}
}
if (ok)
{
if(fileContents == nil)
{
NSLog(@"ReadError: %@", [fileError localizedDescription]);
ok = false;
}
else
{
NSLog(@"Success : %@", fileContents);
}
}
// Clean up
if (someptr)
free(someptr);
[pool drain];
return ok;
精彩评论