美文网首页
iOS 重构利器-类属性

iOS 重构利器-类属性

作者: SoaringHeart | 来源:发表于2018-09-14 15:21 被阅读29次

创建类属性: 
1. 使用@property (class)来声明一个类属性; 
2. 为类属性创建一个存储变量(如果有现成最好),通常为全局变量(例如static NSUUID *_identifier = nil;); 
3. 实现类属性的getter与setter方法,如果是只读属性,只需要实现get;

As mentioned in the release notes these are never synthesised for you so Xcode will warn you if they are missing.
(编译器不会自动帮我们生成类属性的getter和setter方法,如果set,get方法丢失,Xcode会警告提示)

//楼主重构都是基于分类,分类实现不了的才考虑其他方案,示例如下:

@interface UIApplication (Helper)

@property (class, nonatomic, strong, nullable) UIViewController *rootController;
@property (class, nonatomic, strong, nullable) UIWindow * keyWindow;

@end


#import "UIApplication+Helper.h"

@implementation UIApplication (Helper)

+ (UIWindow *)keyWindow{
    UIWindow *window = UIApplication.sharedApplication.delegate.window;
    if (window == nil) {
        window = [[UIWindow alloc]initWithFrame:UIScreen.mainScreen.bounds];
        window.backgroundColor = UIColor.whiteColor;
        [window makeKeyAndVisible];
        UIApplication.sharedApplication.delegate.window = window;
        
    }
    return window;
    
}

+(void)setKeyWindow:(UIWindow *)keyWindow{
    if (keyWindow == nil) return;
    UIApplication.sharedApplication.delegate.window = keyWindow;
    
}

+ (UIViewController *)rootController{
    UIViewController *rootVC = UIApplication.keyWindow.rootViewController;
    return rootVC;
}

+(void)setRootController:(UIViewController *)rootVC{
    if (rootVC == nil) return;
    UIApplication.keyWindow.rootViewController = rootVC;
    
}

//设置根控制器
+ (void)setupRootController:(id)controller{
    if ([controller isKindOfClass:[NSString class]]) controller = [NSClassFromString(controller) new];
    
    if ([controller isKindOfClass:[UINavigationController class]] || [controller isKindOfClass:[UITabBarController class]]) {
        UIApplication.rootController = controller;
        
    }
    else{
        UINavigationController * navController = [[UINavigationController alloc] initWithRootViewController:controller];
        UIApplication.rootController = navController;

    }

}

@end


使用:
    NSString * controlName = @"HomeViewController";
    controlName = @"MainViewController";
   [UIApplication setupRootController:controlName];
 
Objective-C Class Properties:
https://useyourloaf.com/blog/objective-c-class-properties/

相关文章

网友评论

      本文标题:iOS 重构利器-类属性

      本文链接:https://www.haomeiwen.com/subject/rwpogftx.html