Re: [問題] 多重型態處理的方法

看板MacDev作者 (ObjC)時間11年前 (2013/10/18 15:21), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《issuemylove (skill)》之銘言: : 最近想要作一個view,如下 : ┌───────┐ : │ │ : │ UILabel │ : │ │ : │ A │ : │ │ : │ other UIView │ : │ │ : │ │ : └───────┘ : 其中 A view (UIView) 的部分想要動態決定是屬於哪種 view : 例如 A 可能是 UIImageView 或 UITextView 或 UILabel : 我目前的寫法是 定一個 array 裡面存 NSNumber : 也就是說目前 index 在array 第 index 個的時候 : alloc 出對應的 xxx type View : 寫法是 if( index == [NSNumber intValue]) : alloc UIImageView : else if( index == [NSNumber intValue]) : alloc UILabelView : else : .... alloc 其他 type : 然後讓 A = xxx type View. : 可是這樣很蠢啊...Orz : 請問有甚麼好方法可以把 if-else 給拔掉呢? : 謝謝QQ 如果你只是想把alloc簡化成一行 NSString *className = nil; id view = nil; switch(2) { case 1: className = @"UIImageView"; break; case 2: className = @"UILabel"; break; default: className = @"UIView"; break; } if (className) { view = [[NSClassFromString(className) alloc] init]; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.163.107.187

10/18 15:36, , 1F
謝謝你的幫助!!QQ
10/18 15:36, 1F
文章代碼(AID): #1IOE5skZ (MacDev)
討論串 (同標題文章)
文章代碼(AID): #1IOE5skZ (MacDev)