示例代码中的AVFoundation.Framework中的静态void指针

Sag*_*ari 6 static objective-c avfoundation ios

我只是通过示例代码AVFoundation.Framework- > AVSimpleEditoriOS&我发现以下行,我无法理解.

static void *AVSEPlayerItemStatusContext = &AVSEPlayerItemStatusContext;
static void *AVSEPlayerLayerReadyForDisplay = &AVSEPlayerLayerReadyForDisplay;
Run Code Online (Sandbox Code Playgroud)

考虑以下

static void *AVSEPlayerItemStatusContext = nil;
static void *AVSEPlayerLayerReadyForDisplay = nil;
Run Code Online (Sandbox Code Playgroud)

在上面的两行中,我可以看出那些是2个静态的void/generic指针,带有一些奇特的名字.

现在回到这两行,我再次粘贴在这里,

static void *AVSEPlayerItemStatusContext = &AVSEPlayerItemStatusContext;
static void *AVSEPlayerLayerReadyForDisplay = &AVSEPlayerLayerReadyForDisplay;
Run Code Online (Sandbox Code Playgroud)

上面是否意味着,2个静态void/generic指针存储它自己的引用?为什么它需要在什么意义上呢?

我只需要很少的指导来学习这种编码模式.等待知识.

Mar*_*n R 7

一个自引用指针

static void *foo = &foo;
Run Code Online (Sandbox Code Playgroud)

只是一种在编译时创建唯一指针的方法.

"AVSimpleEditoriOS"示例项目中,这些指针稍后用作context参数

[self addObserver:self forKeyPath:@"player.currentItem.status" options:NSKeyValueObservingOptionNew context:AVSEPlayerItemStatusContext];
Run Code Online (Sandbox Code Playgroud)

[self addObserver:self forKeyPath:@"playerLayer.readyForDisplay" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:AVSEPlayerLayerReadyForDisplay];
Run Code Online (Sandbox Code Playgroud)

context参数的实际值根本不重要,它只是传递给它的一些唯一值

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
     if (context == AVSEPlayerItemStatusContext) {
        // Notification for @"player.currentItem.status"
        // ...
     } else if (context == AVSEPlayerLayerReadyForDisplay) {
        // Notification for @"playerLayer.readyForDisplay"
        // ...
     } else {
        // Something else, pass to superclass:
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
Run Code Online (Sandbox Code Playgroud)

(或者,可以检查keyPath参数observeValueForKeyPath.) 请参阅下面的@Bavarious'注释,了解为什么唯一的上下文指针通常比键路径字符串更受欢迎.

  • 只需注意一点:唯一的上下文指针通常比键路径字符串更受欢迎,因为其中一个超类也可能正在观察相同的键路径. (4认同)