0

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.

2 Answers2

2

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.

DrummerB
  • 39,814
  • 12
  • 105
  • 142
  • Thank you for your answer, much appreciated. However, my aim with this (which i should have specified, sorry) is to avoid code replication. – Martin Sommervold Dec 04 '12 at 15:57
  • 1
    How is this replicating code? As DrummerB said, this is a fairly common design pattern. There's no duplicate logic. – csano Dec 04 '12 at 16:00
  • You don't have duplicate code. You move the implementation to the new method and call it from the old one with a `nil` argument. – DrummerB Dec 04 '12 at 16:01
1

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