I have a function that I want to operate on two different custom objects. My first thought was to accept the argument as an (id) and operate on the id object. I can\'t quit
You should try not to access instance variables from another class.
In Objective-C it's enough that the two objects respond to the same selector (say count
), however that would give you a compiler warning.
There are two ways you can get rid of this warning: either by subclassing from a common Fruit
class or by having your two classes conform to a protocol. I'd go with the protocol:
@protocol FruitProtocol
- (NSDecimalNumber *)count;
@end
@interface Orange : NSObject
@end
@interface Apple : NSObject
@end
Then your method can look like this:
-(NSDecimalNumber*)addCount:(id)addFruit {
return [count decimalNumberByAdding:[addFruit count]];
}
Here you are saying that your addCount
expects any object that conforms to the FruitProtocol
protocol, and hence can respond to the count
selector, so the compiler will accept it.