简体   繁体   English

Objective-C:类作为参数

[英]Objective-C: class as parameter

is it possible to create an object of a type class A, knowing that A was passed as a parameter. 是否可以知道A作为参数传递而创建类型为A类的对象? Typically: 通常:

Class A=[MyClass class];
....
A * object=[[A alloc]...]; //incorrect code here !

Thanks ! 谢谢 !

You can't use a variable as the type of a variable. 您不能将变量用作变量的类型。 You need to use id . 您需要使用id

Class A = [MyClass Class];
....
id object = [[A alloc]...];

A is a variable, in fact it is a reference to an object much like all the other objects. A是一个变量,实际上,它是对对象的引用,就像所有其他对象一样。 You can't therefore use it where the compiler is expecting type. 因此,您不能在编译器需要类型的地方使用它。 You should declare object as an id or some other superclass of the types you know that A could be. 您应该将object声明为id或您知道A可能是的其他类型的超类。 The following code works fine, for example. 例如,以下代码可以正常工作。

-(void) testFooBar
{
    Class foo = [NSMutableString class];
    NSString* bar = [[foo alloc] initWithFormat: @"Message: %@", @"Hello, World"];
    NSLog(@"bar is %@, class name %@", bar, [bar className]);
}

And produces the following 并产生以下

2014-04-17 16:29:49.962 BigNumber[62212:303] bar is Message: Hello, World, class name __NSCFString

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM