Using (id) in Objective-C

前端 未结 5 769
独厮守ぢ
独厮守ぢ 2020-12-09 22:01

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

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 22:40

    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.

提交回复
热议问题