iOS: How do I know if a property is KVO-compliant?

前端 未结 4 1060
失恋的感觉
失恋的感觉 2020-11-30 07:36

In the Key-Value Observing Programming Guide, the section Registering for Key-Value Observing says \"Typically properties in Apple-supplied frameworks are only KVO-compliant

4条回答
  •  攒了一身酷
    2020-11-30 08:31

    Here's a solution using Associative References to define an instance variable with a category. But, it doesn't work cause, according to @Dave DeLong, I must use a run-time (not compile-time) check for this.

    // UIWindow+Additions.h
    
    @interface UIWindow (Addtions)
    
    #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_4_0
    @property (retain, nonatomic) UIViewController *rootViewController;
    #endif
    
    @end
    
    // UIWindow+Additions.m
    
    #import "UIWindow+Additions.h"
    #include 
    
    @implementation UIWindow (Additions)
    
    #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_4_0
    @dynamic rootViewController;
    
    static UIViewController *rootViewControllerKey;
    
    - (UIViewController *)rootViewController {
        return (UIViewController *)objc_getAssociatedObject(self, &rootViewControllerKey);
    }
    
    - (void)setRootViewController:(UIViewController *)newRootViewController {
        UIViewController *rootViewController = self.rootViewController;
        if (newRootViewController != rootViewController) {
            // Remove old views before adding the new one.
            for (UIView *subview in [self subviews]) {
                [subview removeFromSuperview];
            }
            [rootViewController release];
            objc_setAssociatedObject(self, &rootViewControllerKey, newRootViewController,
                                     OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            [rootViewController retain];
            [self addSubview:rootViewController.view];
        }
    }
    #endif
    
    @end
    

提交回复
热议问题