Martin Sommervold
Martin Sommervold

Reputation: 152

Changing objective-c method after wide implementation

I have a method which is used widely throughout my app, it looks like so:

-(void)commandWithParams:(NSMutableDictionary*)params command:(NSString *) command method: (NSString *) method onCompletion:(JSONResponseBlock)completionBlock { }

This is used to carry out REST calls to an API. After using it all over the place i realize that i need to add another parameter (which will be used only some of the time), and i'm wondering what the best way to do this is.

I thought about using a using a parameter which defaults to nil if not specified, but apparently this is a no-go in objective c (?)

How should i go about changing it? Do i have to change it everywhere it's called and pass nil? If so, any neat functions in xCode to do this without too much hassle?

Thanks.

Upvotes: 0

Views: 78

Answers (2)

DrummerB
DrummerB

Reputation: 40211

There are no optional arguments in Objective-C. What you could do instead is use two separate methods.

Imagine you had this method:

- (void)methodWithArgument:(NSString *)str {
    // block A
}

Now you need to add a new argument, but don't want to specify it everywhere in your code.

Create a new method with the additional argument and move your implementation to it. How you handle the additional argument, depends on what the method does. From your old method, call the new one with nil as the new argument:

- (void)methodWithArgument:(NSString *)str andArgument:(NSString *)str2 {
    if (str2 != nil) {
        // do something.
    }
    // block A
}

- (void)methodWithArgument:(NSString *)str {
    [self methodWithArgument:str andArgument:nil];
}

This will work as if you had a method with an optional parameter, that defaults to nil (or whatever you chose). It's a common design pattern and you see it all over Apple's frameworks too.

Upvotes: 2

user207128
user207128

Reputation:

As an alternative to the method above you may do refactoring in AppCode. It allows to do such of things.

Upvotes: 1

Related Questions