Objective C — narrow instance variable types in subclasses?

后端 未结 4 613
无人共我
无人共我 2020-12-11 08:02

Is it possible to narrow the allowed type of an ivar in a subclass. Something like this:

@interface person: NSObject {
  NSArray *friendArray;
}

@interface         


        
4条回答
  •  囚心锁ツ
    2020-12-11 08:32

    If the compiler says 'no' then that's your answer. I would use accessors:

    //Person
    -(NSArray *)friends;
    
    
    //MutablePerson
    -(void)addFriend:(person *)friend;
    

    In the MutablePerson you could declare another array to store friends or you could access the ivar directly in addFriend::

    -(void)addFriend:(person *)friend
    {
        _friendsArray = [_friendsArray arrayByAddingObject: friend];
    }    
    

    Accessing ivars directly isn't smart. I would reconsider your class design. What's the rationale for having a mutable and immutable versions of person?

提交回复
热议问题