使用NSClassFromString

使用NSClassFromString

使用NSClassFromString可以直接从字符串初始化出对象出来,即使不引用头文件也没关系,以下是源码:

AppDelegate.m

//
//  AppDelegate.m
//  Class
//
//  Copyright (c) 2014年 Y.X. All rights reserved.
//

#import "AppDelegate.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    Class aClass                   = NSClassFromString(@"RootViewController");
    UIViewController *CV           = [[aClass alloc] init];
    self.window.rootViewController = CV;
    
    self.window.backgroundColor    = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

@end

RootViewController.m

//
//  RootViewController.m
//  Class
//
//  Copyright (c) 2014年 Y.X. All rights reserved.
//

#import "RootViewController.h"

@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor redColor];
}

@end

改进点的方式(直接改装成为category):

NSString+CreateClass.h 与 NSString+CreateClass.m

//
//  NSString+CreateClass.h
//  Class
//
//  Copyright (c) 2014年 Y.X. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NSString (CreateClass)

- (Class)toClass;

@end
//
//  NSString+CreateClass.m
//  Class
//
//  Copyright (c) 2014年 Y.X. All rights reserved.
//

#import "NSString+CreateClass.h"

@implementation NSString (CreateClass)

- (Class)toClass
{
    return NSClassFromString(self);
}

@end

-备注-

这种用法是有着缺陷的呢:

这是在运行时的时候检测出来的,很不保险的说.

 
原文地址:https://www.cnblogs.com/YouXianMing/p/3923828.html