override property from superclass in subclass

前端 未结 2 976
深忆病人
深忆病人 2021-01-06 15:37

I want to override an NSString property declared in a superclass. When I try to do it using the default ivar, which uses the the same name as the property but with an unders

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-06 15:59

    Only the superclass has access to the ivar _species. Your subclass should look like this:

    - (NSString *)species {
        NSString *value = [super species];
        if (!value) {
            self.species = @"Homo sapiens";
        }
    
        return [super species];
    }
    

    That sets the value to a default if it isn't currently set at all. Another option would be:

    - (NSString *)species {
        NSString *result = [super species];
        if (!result) {
            result = @"Home sapiens";
        }
    
        return result;
    }
    

    This doesn't update the value if there is no value. It simply returns a default as needed.

提交回复
热议问题