2013-12-12 100 views
-1

我想創建一個更短,更優雅的版本的一些工作代碼。Objective C removeObjectsAtIndexes願望清潔代碼

僅供參考我必須添加一個元素到現有的數組,然後刪除一個,然後重複。 (不幸的是我不能添加多個元素,然後刪除多個元素)。

工作代碼:

NSMutableArray *destinationArray; 
destinationArray = [[NSMutableArray alloc] init]; 
NSMutableArray *originArray = [[NSMutableArray alloc]init]; 

// Copy one specific array element from originArray to destinationArray 
// Note: assume originArray and destinationArray populated at this point 
int originIndex = var1-var2+1; 
[destinationArray addObject:originArray[originIndex]]; 

// Remove one specific array element from destinationArray 
[destinationIndex removeAllIndexes]; // clear index if used previously 
[destinationIndex addIndex:var3-var4-1]; 
[destinationArray removeObjectsAtIndexes:destinationIndex]; 

我寧願一些版本如下:

[destinationArray addObject:originArray[var1-var2+1]]; 
[destinationArray removeObjectsAtIndexes:[var3-var4-1]]; 

有沒有辦法讓這個短版的工作? (給出預期的標識符錯誤)

感謝很多的幫助...

+0

你的實現是你問什麼不同。你的代碼不會工作,它會崩潰,因爲你沒有在'originArray'中添加任何對象,並且你試圖從空數組中獲取對象。 –

+0

@Bhumeshwerkatre閱讀代碼中的評論。 – rmaddy

+2

爲什麼人們會對這個問題投票?問題很明顯,它顯示了相關的代碼,並且顯示了一些努力。人們還想要什麼? – rmaddy

回答

1

爲什麼不能做到這一點:

NSMutableArray *destinationArray = [[NSMutableArray alloc] init]; 
NSMutableArray *originArray = [[NSMutableArray alloc]init]; 

// somewhere in here objects are added to "originArray" 

[destinationArray addObject:originArray[var1-var2+1]]; 
[destinationArray removeObjectAtIndex:var3-var4-1]; 
+0

什麼是var1,var2,var3,var4在這裏? –

+2

@Bhumeshwerkatre詢問OP。 – rmaddy

+0

幹得好馬迪,謝謝,效果很好。作爲Objective C的新手,我只是有一些額外的括號而已。而Bhumeshwerkatre:變量只是用來設置正確的索引值的整數。 – efromsf