2011-06-01 24 views
0

我有一個具有多個tableviews的應用程序,我想使用Core Data來捕獲所有數據。我有兩個實體 - 冰櫃和物品。在第一個tableview中,我添加了一個冰箱,並且它可以正確保存。我退出了應用程序,重新開放,它就在那裏。我點擊冰箱(打開另一個tableview)並添加一些項目,我可以在我的新的分段tableview中看到它們。我退出我的應用程序,重新啓動它,看到冰箱,點擊它,並沒有任何項目。保存來自多個TableVIews的核心數據

我有我的我的appDelegate managedObjectContext並從那裏使用所有視圖引用它,所以我沒有創建多個實例。下面是我用的物品保存到冰箱的代碼,無論是managedObjectContext和我itemsArray:

Item *item = (Item *)[NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:[delegate managedObjectContext]]; 
    [item setFreezer:freezerName]; 
    [item setName:name]; 
    [item setQuantity:quantity]; 
    [item setSection:section]; 
    [item setAdded:added]; 
    [item setNotes:notes]; 

    NSError *error = nil; 
    if (![[delegate managedObjectContext] save:&error]) { 
     NSLog(@"Freezer info didn't save. Need to handle this."); 
    } 

    [items insertObject:item atIndex:0]; 

這裏是代碼我在ItemViewController使用中viewDidLoad中檢索項:

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"freezer == '%@'", freezerName]; 
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:[delegate managedObjectContext]]; 
    NSSortDescriptor *sorts = [[NSSortDescriptor alloc] initWithKey:@"section" ascending:NO]; 
    NSArray *sort = [[NSArray alloc] initWithObjects:sorts, nil]; 

    [request setSortDescriptors:sort]; 
    [request setEntity:entity]; 
    [request setPredicate:predicate]; 

    NSError *error = nil; 

    NSMutableArray *results = [[[delegate managedObjectContext] executeFetchRequest:request error:&error] mutableCopy]; 
    if(results == nil) { 
     NSLog(@"Error fetching results... need to handle"); 
    } 

    [self setItems:results]; 

    NSLog(@"items count:%d", [items count]); 

返回的物品數量爲零。

我完全難住,花了幾個小時在網上搜索,嘗試不同的事情,我無法弄清楚。我知道有一些更聰明的編碼器,我希望你們其中一位能看到問題所在。

回答

0

所以我的數據被正確保存 - 在我評論謂詞後我看到它。所以我的謂詞的語法是錯誤的。我做了一些搜索,發現這篇文章,其工作對我來說:

Querying Core Data with Predicates - iPhone

我取代LIKE與含有[CD]和它的作品!

0

我想嘗試的謂詞改爲

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"freezer like %@", freezerName]; 

希望幫助!

+0

我欣賞這個建議,但收到相同的結果。 – 2011-06-01 17:42:21

0

也許問題是,你在

- viewDidLoad: 

方法加載數據。它只在加載視圖時調用一次,所以當下層數據被更改時,視圖控制器不知道它。

您可以將您的代碼加載到

- viewWillAppear: 

方法或引入通知來傳播信息的數據存儲已經改變其狀態,並重新加載在該事件表視圖。

最好的方法可能是使用NSFetchedResultsController作爲您的數據源,因爲它始終知道其數據存儲更改。檢查文檔以參考該類。

+0

我試着將代碼移動到viewWillAppear並得到相同的結果。我決定刪除謂詞,我的數據顯示出來很好。所以我知道數據在那裏,我只需要弄清楚爲什麼我的謂詞不起作用。 – 2011-06-02 00:49:37