2012-11-02 237 views
0

我想將一個對象添加到數組內部的數組中。如何將對象添加到數組中的數組?

Screens

這是我的故事板。屏幕A是一個簡單的tableView,包含一個帶有對象A的數組,屏幕B將新的對象添加到屏幕A.每個對象A包含一個包含詳細信息的數組(對象B),這些細節顯示在屏幕C中,並且將細節添加到對象A中屏幕D.

Arrays

所以我的模型,你可以在上面看到。我得到了包含對象A的數組A,每個對象都包含包含對象B的數組B.我的數組都是可變的。

對象A =預算 對象B =項目

我無法弄清楚如何對象B添加到陣列B.

- (void)addItemViewController:(AddItemViewController *)controller didFinishAddingItem:(Item *)item 

    int newRowIndex = [self.budgets.items count]; 
[self.dataModel.budgetsList addObjectFromArray:item]; 

NSLog(@"Item with name %@ added", item.name); 

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:newRowIndex inSection:0]; 
NSArray *indexPaths = [NSArray arrayWithObject:indexPath]; 
[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic]; 

[self dismissViewControllerAnimated:YES completion:nil]; 

這就是我這樣做車費。我的問題在於,我將項目(對象B)添加到預算數組(數組A)中。 :/

在此先感謝。

+2

我不知道你在這裏做什麼或你的問題是什麼。你有點混亂。 'addObjectFromArray:'這個名字意味着它會將另一個**數組中的對象**添加到'budgetsList'中,但是您將單個對象'item'傳遞給它。 – Tobi

回答

0

當你這樣做:

NSArray *indexPaths = [NSArray arrayWithObject:indexPath]; 

您與數據混合演示。你需要的是得到這個索引路徑對應的對象元素(你的情況的數組)。根據Table視圖設計模式,每個表視圖都會從底層的數據對象集合中讀取其單元格。你有沒有定義這個對象(最好是在單獨的Objective-C .m和.h文件中)?

至於添加數組到另一個數組,NSArray只是期望NSObject作爲元素,所以它是非常直接的添加到另一個。

NSArray *arrayB = [[NSArray alloc] init]; //any other initialization is good as well 
NSArray *arrayA= [NSArray arrayWithObject:arrayB]; 

上述代碼適用於代碼中的任何NSArrays對。

+0

我不想將數組添加到其他數組。我想將一個對象添加到另一個數組內的數組中。 – Opstrup

0

如果你想將一個對象添加到數組b中,然後使用:

[[[array A objectAtIndex:indexPath] arrayB] addObject:yourObject]; 

或者您可以使用(這是上面的代碼擴展):

ObjectA *temp = [array A objectAtIndex:indexPath]; 

NSMutableArray *tempArray = [temp arrayB]; 

[tempArray addObject:yourObject]; 
+0

還有問題嗎? –

+0

是的,我真的不能做這項工作。這是我正在嘗試如此的票價\t'int newRowIndex = [self.budgets.items count]; [[[self.dataModel.budgetsList objectAtIndex:newRowIndex] items] addObject:item];'但我現在得到一個錯誤:「NSArray沒有可見的@interface聲明選擇器addObject」我不知道這是什麼意思.. :/ – Opstrup

+0

@Opstrup:您無法使用addObject方法將對象添加到「NSArray」。更改數組類型爲'NSMutableArray' –

0

投下你的對象B到Item然後做

[self.dataModel.budgetList replaceObjectAtIndex:11 withObject:(Item)item]; 

此代碼假設你要替換A和T內的現有對象他的索引是11.如果你想添加你只是使用insertObjectAtIndex: withObject:

+0

我不知道你的意思是把我的對象B到項目?你能鏈接任何關於轉換的文檔,或者可以解釋它的含義嗎?這是我的第一個應用程序,對不便: – Opstrup