Possible Duplicate:
Objective-C Default Argument Value
I couldn't find a way to define a default argument to a function in ios like you would normally do in C++. Is it possible in iOS? If not is there a work around recommended?
Possible Duplicate:
Objective-C Default Argument Value
I couldn't find a way to define a default argument to a function in ios like you would normally do in C++. Is it possible in iOS? If not is there a work around recommended?
This isn't possible in Objective-C. One option is to do something like this to get the same functionality:
- (void)someMethodThatTakesAString:(NSString *)string
{
if (string == nil) string = @"Default Value";
// Use string
}
If you're looking for the ability to omit an argument altogether, the typical way that's done in Objective-C is to have multiple methods with progressively more specific argument sets:
- (void)doSomethingWithOptionA:(BOOL)optionA andOptionB:(int)optionB
{
// Do something using options to control exactly what's done
}
- (void)doSomethingWithOptionA:(BOOL)optionA
{
[self doSomethingWithOptionA:optionA andOptionB:42]; // Where 42 is the default for optionB
}
- (void)doSomething;
{
[self doSomethingWithOptionA:NO]; // NO is the default for optionA
}
Then if you want to doSomething with just the default arguments, you can just call -doSomething
. If you want to set optionA, but don't care about optionB, you can call -doSomethingWithOptionA:
etc.
Finally, it's worth noting that you can use C++ to write for iOS, and you can also mix Objective-C and C++ using Objective-C++. All that said, always think carefully about how best to do things within the environment you're using. Don't try to force C++ idioms and patterns onto Objective-C and Cocoa. They're different and they're meant to be that way. It's often very easy to spot a C++ programmer who hasn't given up C++ conventions when transitioning to writing Objective-C code, and that's usually not a good thing.
Take a look at answers here: Objective-C Default Argument Value
What you should do is define a method that takes all the arguments and then write convenience methods that take fewer arguments, then turn around and call the longer method with the default values you want