I am just going through the sample code of AVFoundation.Framework
-> AVSimpleEditoriOS
& I found following line which I could not understand.
static void *AVSEPlayerItemStatusContext = &AVSEPlayerItemStatusContext;
static void *AVSEPlayerLayerReadyForDisplay = &AVSEPlayerLayerReadyForDisplay;
consider following
static void *AVSEPlayerItemStatusContext = nil;
static void *AVSEPlayerLayerReadyForDisplay = nil;
Above two lines, I can figure out that those are 2 static void/generic pointers with some fancy name.
Now back to those 2 lines, I am pasting it here again,
static void *AVSEPlayerItemStatusContext = &AVSEPlayerItemStatusContext;
static void *AVSEPlayerLayerReadyForDisplay = &AVSEPlayerLayerReadyForDisplay;
Does above mean, 2 static void/generic pointers storing reference of it's own & why would be it needed in what sense?
I just need little guide to learn such coding pattern. Awaiting for knowledge.
A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typcasted to any type. Note that the above program compiles in C, but doesn't compile in C++. In C++, we must explicitly typecast return value of malloc to (int *).
2) void pointers in C are used to implement generic functions in C. For example compare function which is used in qsort().
A self-referencing pointer
static void *foo = &foo;
is just a method to create a unique pointer at compile time.
In that "AVSimpleEditoriOS" sample project, these pointers are later used as context
parameter for
[self addObserver:self forKeyPath:@"player.currentItem.status" options:NSKeyValueObservingOptionNew context:AVSEPlayerItemStatusContext];
and
[self addObserver:self forKeyPath:@"playerLayer.readyForDisplay" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:AVSEPlayerLayerReadyForDisplay];
The actual value of the context parameter does not matter at all, it is just some unique value that is passed to
- (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];
}
}
(Alternatively, one could check the
See @Bavarious' comment below for why unique context pointers are generally preferred over key path strings.keyPath
parameter in observeValueForKeyPath
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With