updateTrackingAreas 使用 objective-c ... 使用 super 和 alloc

updateTrackingAreas using objective-c ... use of super and alloc

我需要跟踪鼠标移动位置。理想情况下,我想使用 "setAcceptsMouseMovedEvents",它将被 window 或子类 NSView 捕获。但我不确定把它放在哪里。因此,我将通过 updateTrackingAreas 跟踪鼠标移动。

- (void) updateTrackingAreas {
    [self removeTrackingArea:trackingArea];
    trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds]
        options:(NSTrackingActiveAlways | NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved)
        owner:self userInfo:nil];
    [self addTrackingArea:trackingArea];
    [super updateTrackingAreas];
}

我的问题是:

  1. 代码中使用了alloc。我需要释放这个吗?如果可以,在哪里做?

  2. 在代码的末尾,调用了"super"。我把它放在那里是因为通常建议调用 parent。但是,我只跟踪一个区域,所以我不确定是否需要它。有人可以告诉我是否真的需要吗?

  3. 既然没有使用setAcceptsMouseMovedEvents,我还需要使用NSTrackingActiveWhenFirstResponder吗?我好像不是,但我可能是错的?

感谢您的帮助

  1. 如果ARC (Automatic Reference Counting)开启,ARC将释放trackingArea

  2. 来自updateTrackingAreas的文档:

your implementation should call super.

  1. 来自 NSTrackingActiveWhenFirstResponder
  2. 的文档

The owner receives messages when the view is the first responder. This value specifies when the tracking area defined by an NSTrackingArea object is active.