user142019
user142019

Reputation:

How can I combine methods with different arguments?

I have four main methods:

+ (NSArray *)findAll;
+ (NSArray *)findAllWithOrder:(NSArray *)order;
+ (NSArray *)findAllWithConditions:(NSDictionary *)conditions;
+ (NSArray *)findAllWithLimit:(NSRange)limit;

In addition, I want to combine these methods (so I can find all by both order and conditions, for example). Currently I'm doing (all possibilities even with arguments in a different order not shown here):

+ (NSArray *)findAll;
+ (NSArray *)findAllWithOrder:(NSArray *)order;
+ (NSArray *)findAllWithConditions:(NSDictionary *)conditions;
+ (NSArray *)findAllWithLimit:(NSRange)limit;
+ (NSArray *)findAllWithOrder:(NSArray *)order conditions:(NSDictionary *)conditions;
+ (NSArray *)findAllWithOrder:(NSArray *)order limit:(NSRange)limit;
+ (NSArray *)findAllWithConditions:(NSDictionary *)conditions limit:(NSRange)limit;
+ (NSArray *)findAllWithOrder:(NSArray *)order conditions:(NSDictionary *)conditions limit:(NSRange)limit;

But is there a simpler way than creating dozens of methods for this? That would be very nice. Thanks.

Upvotes: 1

Views: 100

Answers (4)

zbyhoo
zbyhoo

Reputation: 1

For me it looks like a candidate for Builder design pattern (http://en.wikipedia.org/wiki/Builder_pattern)

You create i.e. Finder class with methods:

-(void)searchOrder:(NSArray *)order;

-(void)searchCondition(NSDictionary *)conditions;

and so on... These methods sets object's members to values you pass in these methods.

These methods are optional, so you can call (on object of Finder class) none of them (final effect like + (NSArray *)findAll; in your situation) or some of them.

In the end you call on Finder's object method i.e. -(NSArray *)find; and you have results.

Upvotes: 0

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81868

Go with the one that has all the arguments (findAllWithOrder:conditions:limit:) and use nil to identify unused arguments (or, in case of NSRange, { NSNotFound, 0 })

Upvotes: 3

Jacob Relkin
Jacob Relkin

Reputation: 163288

The way Apple accomplishes this is, in my opinion, one of the best ways to do it in Obj-C:

Define a catch-all method that takes an options dictionary or bitmask, and then have logic inside the method that based on the dictionary or bitmask, would execute the appropriate code.

Upvotes: 2

kubi
kubi

Reputation: 49364

Nope, that's the way you do it. I'm sure someone could find ways to get around creating dozens of similar methods, but they are very rarely used. It's pretty common for Obj-C (esp. Cocoa) objects to have large numbers of methods that differ from each other only slightly.

Upvotes: 0

Related Questions