2012-11-19 66 views
1

性質,我發現一些代碼,看起來像:遍歷在Objective-C

if (statisticsObject.idag3_orig != 0) { 
    statisticsView.idag3.text = [NSString stringWithFormat:@"%i",statisticsObject.idag3_orig]; 
} else { 
    float compare1 = statisticsObject.idag2; 
    float compare2 = statisticsObject.idag3; 
    float result = compare1 + (compare1 * (compare2/(float) 100.00)); 
    int final = (int)roundf(result); 
    statisticsView.idag3.text = [NSString stringWithFormat:@"%i",final]; 
} 

if (statisticsObject.igar3_orig != 0) { 
    statisticsView.igar3.text = [NSString stringWithFormat:@"%i",statisticsObject.igar3_orig]; 
} else { 
    float compare1 = statisticsObject.igar2; 
    float compare2 = statisticsObject.igar3; 
    float result = compare1 + (compare1 * (compare2/(float) 100.00)); 
    int final = (int)roundf(result); 
    statisticsView.igar3.text = [NSString stringWithFormat:@"%i",final]; 
} 

這樣重複很多次。顯然,它不會很乾,並且有點痛苦。我如何循環這個邏輯與變量屬性名稱? Objective-C不允許我採取的方法。下面是我的嘗試:

NSArray * properties = [[NSArray alloc] initWithObjects: 
               @"foo", 
               @"bar", 
               @"spam", 
               nil]; 
for (id prop in properties) { 
    NSLog(@"%@",obj.prop); 
} 

- 注意 -

我原來的僞代碼是相當混亂。對於那個很抱歉。

簡而言之,我怎樣才能重構我的代碼,以免我不斷重複自己?所執行的數學運算總是相同的。

回答

0

我不;噸瞭解你的第二個代碼,這是什麼,如果你要打印的字符串,將工作:

NSArray * properties = [[NSArray alloc] initWithObjects: 
              @"foo", 
              @"bar", 
              @"spam", 
              nil]; 
for (id obj in properties) { 
    NSLog(@"%@",obj); 
} 
+0

啊,對不起,這是一個有點混亂。如果對象是'obj',我想遍歷它的屬性,有效地做'NSLog(@「%@」,obj.foo);',然後'NSLog(@「%@」,obj.bar); '等 –

1

這主要是架構問題。爲什麼'foo1','foo2'和'foo3'沒有被分組到一個對象中?它們是整數,爲什麼不使用具有三個整數屬性的對象x,yz?然後定義這種對象的一個​​方法updateText,並呼籲:

NSArray * properties = [[NSArray alloc] initWithObjects: 
               obj.foo, 
               obj.bar, 
               obj.spam, 
               nil]; 
for (MyObject* object in properties) { 
    [object updateText]; 
} 

當然,你要的是還可以,訪問的OBJ-C運行時。最簡單的解決方案是使用NSSelectorFromString,例如

SEL sel1 = NSSelectorFromString([NSString stringWithFormat:@"%s%i", @"foo", 1]); 

然後用performSelector,也有NSInvocation得到基本類型。

+0

我想我現在只會把自己和其他人混淆。我用我正在使用的實際代碼更新了我的問題,而不是僞代碼。 –

+0

我的答案仍然有效,將所有'idag ...'和'igar ...'屬性抽象爲一個對象,並在其上創建一個方法。名爲'idag1','idag2'和'idag3'的屬性肯定是錯誤的。應該只有一個名爲'idag'的屬性具有屬性來訪問浮點數'1'' 2'和'3' - 當然,更好的名稱只是數字。 – Sulthan

+0

對不起,我已經嘗試了很多方法,而我卻無法完成它的工作。我正在使用ARC,它可以防止隱式類型轉換。這感覺好像比它需要的複雜得多。爲什麼迭代某些屬性很難?爲什麼我不能僅僅切換變量的屬性名稱?這就是我現在要做的工作:http://pastie.org/5401172 –

0

有了一定的照顧這個代碼應工作:

NSArray * properties = [[NSArray alloc] initWithObjects: 
         @"foo", 
         @"bar", 
         @"spam", 
         nil]; 
for (id obj in properties) 
{ 
    SEL selector = NSSelectorFromString(obj); 
    if (selector && [statisticsView respondsToSelector:selector]) 
     NSLog(@"%@",[statisticsView performSelector:selector]); 
} 

請注意NSLog的可能打破,如果你的屬性不返回一個NSObject

+0

無法使其正常工作。我認爲我的原始僞代碼很混亂。對於那個很抱歉。我已經更新了我的問題。 –