Objective C - 如何实例化保存为变量的类

use*_*959 2 class objective-c instance

我是Objective C的新手,我对这个概念感到困惑.

以下方法应该创建作为参数传递的类的实例并编辑实例的变量.

- (void) createObject:(Class)objecttype atPoint: (CGPoint)position {

    if ([objecttype isSubclassOfClass:[GameObject class]]){

        id theobject = [[objecttype alloc] init];

        theobject.x = position.x; //error
        theobject.y = position.y; //error
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到上面显示的错误消息: Property 'x' not found on object of type '__strong id'

看起来它应该很简单,但我不明白什么是错的.

bbu*_*bum 6

点表示法不会调用类型对象上的方法id.

将该分配行更改为:

GameObject *theobject = (GameObject*)[[objecttype alloc] init];
Run Code Online (Sandbox Code Playgroud)

注意,由于isSubclassOfClass:条件,上面的演员是正确的.