zoukankan      html  css  js  c++  java
  • 使用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

    -备注-

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

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

     
  • 相关阅读:
    java配置文件读取
    简易表单验证
    Enter键提交表单
    background-attachment:fixed应用
    随机生成密钥
    javascript/jquery判断是否为undefined或是null!
    jQuery获取和设置disabled属性、背景图片路径
    $(function(){})里面不能声明定义函数
    CSS浏览器兼容性----Hack
    数组快速排序
  • 原文地址:https://www.cnblogs.com/YouXianMing/p/3923828.html
Copyright © 2011-2022 走看看