来自MapBox的Route-Me我看到iVars的实现方式如下:
@implementation RMMapView
{
BOOL _delegateHasBeforeMapMove;
BOOL _delegateHasAfterMapMove;
BOOL _delegateHasBeforeMapZoom;
BOOL _delegateHasAfterMapZoom;
BOOL _delegateHasMapViewRegionDidChange;
BOOL _delegateHasDoubleTapOnMap;
BOOL _delegateHasSingleTapOnMap;
BOOL _delegateHasSingleTapTwoFingersOnMap;
BOOL _delegateHasLongSingleTapOnMap;
BOOL _delegateHasTapOnAnnotation;
BOOL _delegateHasDoubleTapOnAnnotation;
BOOL _delegateHasTapOnLabelForAnnotation;
BOOL _delegateHasDoubleTapOnLabelForAnnotation;
BOOL _delegateHasShouldDragMarker;
BOOL _delegateHasDidDragMarker;
BOOL _delegateHasDidEndDragMarker;
BOOL _delegateHasLayerForAnnotation;
BOOL _delegateHasWillHideLayerForAnnotation;
BOOL _delegateHasDidHideLayerForAnnotation;
BOOL _constrainMovement;
RMProjectedRect _constrainingProjectedBounds;
float _lastZoom;
CGPoint _lastContentOffset, _accumulatedDelta;
BOOL _mapScrollViewIsZooming;
}
也就是说,它是在.m文件而不是.h文件中声明的。 如果我对这个RMMapView进行子类化,我看不到这些iVars。有没有办法让它在子类中可见,而不是在世界上?
我打算保留原始代码,因此选择子类并从那里修改行为。但也许只是直接更改文件并通过git从主存储库更新代码是一种更好的方法吗?
答案 0 :(得分:1)
在Objective-C中(与其他OO语言一样),大多数开发人员认为实例变量是定义类的实现细节。不应该由其他类直接访问它们。
在这种情况下,实例中声明了实例变量,这是RMMapView
的作者不希望将变量暴露给外部代码的强烈暗示。
答案 1 :(得分:0)
如果您确实希望子类可以看到实例变量,则需要在@interface
中声明它们,而不是@implementation
。
@interface RMMapView : NSObject
{
@protected
BOOL _delegateHasBeforeMapMove;
BOOL _delegateHasAfterMapMove;
BOOL _delegateHasBeforeMapZoom;
BOOL _delegateHasAfterMapZoom;
BOOL _delegateHasMapViewRegionDidChange;
BOOL _delegateHasDoubleTapOnMap;
BOOL _delegateHasSingleTapOnMap;
BOOL _delegateHasSingleTapTwoFingersOnMap;
BOOL _delegateHasLongSingleTapOnMap;
BOOL _delegateHasTapOnAnnotation;
BOOL _delegateHasDoubleTapOnAnnotation;
BOOL _delegateHasTapOnLabelForAnnotation;
BOOL _delegateHasDoubleTapOnLabelForAnnotation;
BOOL _delegateHasShouldDragMarker;
BOOL _delegateHasDidDragMarker;
BOOL _delegateHasDidEndDragMarker;
BOOL _delegateHasLayerForAnnotation;
BOOL _delegateHasWillHideLayerForAnnotation;
BOOL _delegateHasDidHideLayerForAnnotation;
BOOL _constrainMovement;
RMProjectedRect _constrainingProjectedBounds;
float _lastZoom;
CGPoint _lastContentOffset, _accumulatedDelta;
BOOL _mapScrollViewIsZooming;
}
顶部的@protected
限定了可见性,它也可以是@public
或@private
。 @protected
是默认设置,但最好明确地将其显示为显示您故意希望这些ivars对子类可见。