2011-05-28 68 views
0

的名字,如果我創建一個類的對象,我做的:對象與字符串

Item *item01 = [[Item alloc] init]; 

,但我怎麼給它一個名字,我有一個字符串? (我提出這個問題是因爲我必須在一個循環中做到這一點,而對象的名稱是動態的)

NSString *aString = [NSString stringWithFormat:@"%@", var]; 
Item *??? = [[Item alloc] init]; 

謝謝!

+3

[' 「不,你不明白,」 騎士說,看起來有點煩惱。 「這就是名字 的名字,名字真的是'老年人,老年人'。''](http://homepages.tcp.co.uk/~nicholson/alice.html) – sehe 2011-05-28 20:39:58

+1

[Object在Objective-C中String的名稱(http://stackoverflow.com/questions/3888935/object-name-from-string-in-objective-c) – outis 2011-05-28 20:52:37

回答

2

如果你想的名稱來指代對象字符串,您可以將對象存儲在NSMutableDictionary中,並將該鍵設置爲該名稱。

例如:

// Someplace in your controller create and initialize the dictionary 
NSMutableDictionary *myItems = [[NSMutableDictionary alloc] initWithCapacity:40]; 

// Now when you create your items 
Item *temp = [[Item alloc] init]; 
[myItems setObject:temp forKey:@"item01"]; 
[temp release]; 

// This way when you want the object, you just get it from the dictionary 
Item *current = [myItems objectForKey:@"item01"]; 
+0

工作正常,但如果我想從SuperView中刪除item01,我呢?這樣做,它不起作用'[[myItems objectForKey:@「item01」] removeFromSuperview];' – Vins 2011-05-29 14:13:15

+0

所以你的Item對象的超類是UIView?如果是這樣,你應該閱讀[UIView繼續存在後removeFromSuperview](http://stackoverflow.com/questions/1514205/uiview-continues-to-exist-after-removefromsuperview) – 2011-05-29 16:38:22

3

您不能從字符串中獲取變量名稱。你想在這裏做什麼?您可以使用字典從字符串鍵查找變量。

入住此類似question

1

需要改變一個變量(Item *???)的名稱是非常不尋常 - 它往往濫用預處理。

相反,我想你可能正在尋找按名稱創建實例的類型。

要做到這一點使用id,Class apis,NSClassFromString的組合。

id是指向一個未定義objc對象,編譯器將「接受」的任何聲明的消息給:

id aString = [NSString stringWithFormat:@"%@", var]; 

現在可以請求aString執行選擇它可能不響應。它類似於objc類型的void*。請注意,如果您使用不響應的選擇器發送id變量,您將獲得運行時異常。

接下來,Class類型:

Class stringClass = [NSString class]; 
NSString * aString = [stringClass stringWithFormat:@"%@", var]; 

這一切結合起來的名稱,以創建類型的實例:

NSString * className = [stringClass stringWithFormat:@"%@", var]; 
Class classType = NSClassFromString(className); 
assert(classType && "there is no class with this name"); 
id arg = [[classType alloc] init];