//1. 声明一个静态上下文:
static void *changePageContext = &changePageContext;
//2。在 viewDidLoad 中,将 self 作为观察者添加到 QLPreviewController 的强引用的 currentPreviewItemIndex 属性:
[self.previewController addObserver:self forKeyPath:@"currentPreviewItemIndex" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:changePageContext];
//3. 实现观察者方法:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context
{
if (context == changePageContext)
{
NSLog(@"newValue:%ld",(long)self.previewController.currentPreviewItemIndex);
}
else
{
// Any unrecognized context must belong to super
[super observeValueForKeyPath:keyPath
ofObject:object
change:change
context:context];
}
}
//4. 移除 viewWillDisappear 中的观察者:
-(void)viewWillDisappear:(BOOL)animated
{
if (![[self.navigationController viewControllers] containsObject: self])
{
[self.previewController removeObserver:self forKeyPath:@"currentPreviewItemIndex"];
}
}