2013-07-12 40 views
2

我是Objective C的新手,我對此概念感到困惑。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 
    } 
} 

我得到一個錯誤信息,其中上面所指出的:Property 'x' not found on object of type '__strong id'

現在看來似乎應該是簡單的,但我不明白什麼是錯。

回答

6

點符號不會調用類型爲id的對象上的方法。

更改該分配行:

GameObject *theobject = (GameObject*)[[objecttype alloc] init]; 

需要注意的是,由於isSubclassOfClass:有條件的,上面鑄恰恰是正確的。

+0

如果您認爲自己找到了最佳答案,則應該接受答案。人們會更傾向於在將來幫助你 –

+0

在我的情況下,我有一個'類 myClass'對象,但我不能實例化它。 '[[myclass alloc] init]'說沒有選擇器'alloc'的已知類方法。 – Rivera