开发者

How can I combine methods with different arguments?

开发者 https://www.devze.com 2023-01-07 11:49 出处:网络
I have four main m开发者_StackOverflow社区ethods: + (NSArray *)findAll; + (NSArray *)findAllWithOrder:(NSArray *)order;

I have four main m开发者_StackOverflow社区ethods:

+ (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.


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 })


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消