Dukeland
Dukeland

Reputation: 146

How to check if a variable is of type "void" in Objective C?

Here is the case. I forgot to return nil at the end of a method and caused a bad access error in the following code.

- (NSString*) testWithRet{
    NSString* ret = @"js";
    //return ret;
}

...

NSString* var = [obj testWithRet];
//can I check here to prevent the bad access below?
NSLog(@"%@", var); // bad access here

My question is, can I do any checking before the bad access occurs?

I have tried to check "var" against nil and NULL but failed.

Thanks.

Upvotes: 0

Views: 557

Answers (2)

Shashank
Shashank

Reputation: 1753

Check this out:

NSString* var = [obj testWithRet];
//can I check here to prevent the bad access below?
if([var isKindOfClass:[NSString class]]) {
    NSLog(@"%@", var); // bad access here
}

Upvotes: -1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

No, you cannot do any checking like that: letting a value-returning function end without return is undefined behavior, the value "returned" in such cases is, well, undefined.

You need to watch out for warnings in Xcode, and fix them all. In this particular case you should get a message that says

Control reaches end of non-void function

on the line of the closing curly brace of your non-void function. This should be your signal to add a missing return to your code.

Upvotes: 3

Related Questions