alik
alik

Reputation: 2374

How to generalize code calling the same methods on separate objects with no shared interface?

I have an Objective-C project in Xcode 7.3.1.

The project code consumes a third-party library which has three distinct objects A, B and C. The objects have no common parent (except NSObject) nor they are implementing a common relevant interface or protocol. All three objects implement the following methods:

- (id)dataForKey:(NSString *)key;
- (void)setData:(id)value forKey:(NSString *)key;
- (void)removeDataForKey:(NSString *)key;

My code is consuming these methods on these three objects and is doing the same exact operation on them like

BOOL found = NO;

if ([a dataForKey:key] != nil) {
    found = YES;
}
[a removeDataForKey:key];

if ([b dataForKey:key] != nil) {
    found = YES;
}
[b removeDataForKey:key];

if ([c dataForKey:key] != nil) {
    found = YES;
}
[c removeDataForKey:key];

return found;

I would like to generalize the code to something like

- (BOOL)removeFromObject:(id)object {
    BOOL found = NO;
    if ([object dataForKey:key] != nil) {
        found = YES;
    }
    [object removeDataForKey:key];
    return found;
}



return [self removeFromObject:a] || [self removeFromObject:b] || [self removeFromObject:c];

How to pass the three objects into the removeFromObject method while keeping the code as type-safe and strongly typed as possible (as such I do not prefer a solution to pass a generic object to the removeFromObject method and than cast the passed generic object to one of the three objects)?

Upvotes: 0

Views: 22

Answers (1)

trapper
trapper

Reputation: 12003

You use a protocol for this.

@protocol MyProtocol <NSObject>
- (id)dataForKey:(NSString *)key;
- (void)setData:(id)value forKey:(NSString *)key;
- (void)removeDataForKey:(NSString *)key;
@end

So you method definition becomes.

- (BOOL)removeFromObject:(id<MyProtocol>)object;

Upvotes: 1

Related Questions