【问题标题】:how to instantiate an object of class from string in Objective-C?如何从Objective-C中的字符串实例化一个类的对象?
【发布时间】:2011-01-14 15:48:44
【问题描述】:

我有一个字符串,它的值是必须实例化的 Class[MyClass] 的名称,而 MyClass 有一个名为

的方法
 -(void)FunctionInClass;

我正在使用名为 NSClassFromString 的方法来实例化 MyClass。我想知道

1) what does NSClassFromString return?? 
2) what is id? 
3) How to call method -(void)FunctioninClass which is in MyClass using the instance.

我应该如何进行,我是在 Objective-C for iPhone 应用程序中进行的?

【问题讨论】:

    标签: objective-c instantiation


    【解决方案1】:

    1) what does NSClassFromString return??

    它返回一个类,这意味着你可以做[[NSClassFromString(@"MyClass") alloc] init]; 请参阅Mac Dev Center Docs 了解更多信息。

    2) what is id?

    http://www.otierney.net/objective-c.html#idtype

    3) How to call method -(void)FunctioninClass which is in MyClass using the instance.

    id myclass = [[NSClassFromString(@"MyClass") alloc] init];
    [myclass FunctioninClass];
    

    【讨论】:

    • AFAICT,NSClassFromString 是一个函数,而不是一个类。第 1 点将变为 NSClassFromString(@"MyClass")
    • @ point 1) 如果 NSClassFromString 返回一个类,那么该类必须被实例化 n 然后我们可以调用 FunctioninClass 方法对吗?但是@点3)我们直接使用名为myclass的类和调用函数。我尝试了第 3 点)它给了我一个错误:MyClass undeclared(first use in function) and myclass undeclare (first use in function)
    • 试试这样:id myclass= [[NSClassFromString(@"MyClass") alloc] init];如果调用代码不知道 MyClass 是什么,您将收到您描述的错误。通过使用 id 作为变量类型,您可以避免这种情况。
    • 如果在FunctioninClass中设置断点,断点会被命中吗?
    • 这是一个简单的可可应用程序,似乎可以满足您的需求。我创建了一个名为“Untitled”的新 Xcode 项目。 pastee.org/ps83z
    【解决方案2】:

    NSClassFromString() 是一个返回 Objective-C 类的函数。也就是说,在 Objective-C 中,一个类是一个可敬的对象。 “Class”类的一个实例......

    Objective-C 类有什么用?

    用于实例化对象(通过 alloc init ) 用于自省和反射 - 查询该类的方法和属性实例向用户公开 用于归档/取消归档该类的实例,以及... 能够运行类方法(不需要该类的任何特定实例的方法。

    您的最后几行实际上创建了一个类的实例,其名称是传递给 NSClassFromString 的字符串。

    【讨论】:

      猜你喜欢
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 1970-01-01
      • 2018-08-09
      • 2011-10-19
      • 1970-01-01
      相关资源
      最近更新 更多