2013-03-20 125 views
0

所有在我的標題,我想創建一些動態名稱,分配一些differents UIViews,但隨機。例如,我想打:爲UIViews創建動態名稱

Level1 * level1view = [[Level1 alloc] init]; 

所以我嘗試做一些NSString的是這樣的:

ClasseMap = [NSString stringWithFormat:@"Level%i", Map]; 
NomMap = [NSString stringWithFormat:@"level%iview", NumeroMap]; 
id nouveau = NSClassFromString(ClasseMap); 
nouveau * ViewTest; 
ViewTest = [self valueForKey:NomMap]; 
ViewTest = [[nouveau alloc] init]; 

但它給我:未聲明的標識符「ViewTest」的使用。我該如何修復它?我怎樣才能訪問一些變量(例如,level1view.example = YES;)?

感謝您的幫助! =)

+1

請參閱http://stackoverflow.com/questions/2226611/how-to-instantiate-an-object-of-class-from-string-in-objective-c – 2013-03-20 23:05:38

+0

哦,非常感謝! – user2057209 2013-03-20 23:06:50

+0

但是,如何爲名稱,就像我的例子「leve1view」,因爲我把「NSClassFromString(ClasseMap)* NSClassFromString(NomMap)= [[NSClassFromString(ClasseMap)alloc] init];」但它不工作:( – user2057209 2013-03-20 23:11:46

回答

0

爲什麼不寧願保留一個視圖數組呢?

int Map = 0; 
int NumeroMap = 1; 

NSMutableArray *array = [[NSMutableArray alloc] init]; 

//add your views (levels?) to the array 
[array addObject:someUIView]; 
[array addObject:someOtherUIView]; 

//now you can use your indexes to access the views you want 
UIView *yourView = [array objectAtIndex:Map]; 
UIView *anotherView = [array objectAtIndex:NumeroMap]; 

我認爲你想要做的不是去做事情的方式。

+0

我不能採取一個相當的觀點,因爲我創建一個無限的遊戲,所以算法選擇哪個視圖他想打印,但他們之前沒有聲明(打印事項) – user2057209 2013-03-20 23:26:12