2011-07-17 51 views
0

我想知道如何以編程方式更新核心數據對象。該對象雖然是NSSet。因此,我可以用下面的方式總結一下:如何使用核心數據存儲NSSet(一對多)?

Property 
--------- 
name 
price 
typology 

Property_has_typology 
--------------------- 
typology_id 
property 

,該場所和Property_has_typology之間的一個一對多的關係。作爲一個物業可能有幾種類型(又名類別),如牀&早餐,別墅,酒店,大廈,鄉間別墅。

所以我讓用戶在我的TableView中選擇多行,當他點擊保存我想存儲這些更改。所以,我做的:

NSMutableArray *storeItems = [[NSMutableArray alloc] init]; 

//Get selected items 
for (int i = 0; i < [items count]; i++) { 
    Properties_has_typology *typo = [NSEntityDescription insertNewObjectForEntityForName:@"Properties_has_typology" 
                    inManagedObjectContext: [PropertyProvider sharedPropertyProvider].context]; 
    typo.typology_id = [NSNumber numberWithInt: (int)[items objectAtIndex:i]]; 
    typo.property = property; 
    [storeItems addObject: typo]; 
} 

//Store the items for the Property and save it 
if ([storeItems count] > 0) { 
    NSLog(@"Going to save..."); 
    NSSet *storeSet = [[NSSet alloc] initWithArray:storeItems]; 
    property.typology = storeSet; 

    [property save]; 

    [storeSet release]; 
} 

這有點兒工作,問題是,雖然它並沒有真正更新現有的值。它只是壓倒它。所以,如果我救了相同的兩個項目兩次(就像一個例子)我會得到我的數據庫中以下內容:

PK TYPOLOGY 
------------ 
1 | 
2 | 
3 | 4 
4 | 6 

所以,是的,他們正在儲存,但是也帶來了空行(清除它們而不是刪除/更新它們)。

任何幫助,將不勝感激。謝謝!

回答

0
//call 
NSArray* oldTypos = [property.typology allObjects]; 
[[property removeTypology:[PropertyProvider sharedPropertyProvider].context]; 
[[property addTypology:storeSet]; 
for(int i = 0; i < [oldTypos count]; i++){ 
[[PropertyProvider sharedPropertyProvider].context deleteObject:[oldTypos:objectAtIndex:i]]; 
} 
Error* error = nil; 
if(![[PropertyProvider sharedPropertyProvider].context save:&error]){ 
abort(); 
} 
//Also, rename the to-many relationship to plural. 

道歉有任何錯別字。我現在在我的Windows機器上,所以我無法檢查它。

+0

看起來''deleteObject'確實是我正在尋找的東西。現在我可以完全刪除所有條目並插入新條目。謝謝! – Jules

0

TechZen說:我,我顛倒父所描述的一對多關係,事後才注意到。但是,一切都以同樣的方式工作。當我找到時間時我會編輯。

您正在努力通過手動執行Core Data自動執行的操作。要設置一個關係,您只需設置它的一側,並且託管對象上下文自動設置另一側。

所以,如果你有這樣一個數據模型:

Property{ 
    typology<<-->Property_has_typology.properties 
} 

Property_has_typology{ 
    properties<-->>Property.typology 
} 

然後設置從Property物體側的關係,你只需使用:

aPropertyObject.typology=aProperty_has_typologyObject; 

設置如果從Property_has_typology對象方面你使用關係訪問器方法在實現(.m)中爲你的Core Data生成:

[aProperty_has_typologyObject addPropertiesObject:aPropertyObject]; 

[aProperty_has_typologyObject addPropertiesObjects:aSetOfPropertyObjects]; 

...和你做。

如果您必須手動管理所有對象關係,則核心數據不會提供太多實用工具。

+0

是的我已經設置了所有這些功能,但是當我使用這些方法時,它仍然存儲對數據庫中其他參考的引用。所以我做'[property addTypologyObject:typo];'但似乎**添加**它。即使做'[property removeTypology:property.typology];'(應該刪除整個類型的引用imo)它仍然保留記錄在我的問題中所述的數據庫中。 – Jules

+0

從關係中刪除對象不會刪除它,它只是切斷關係。如果你想刪除一個對象,你需要使用'[NSManagedObjectContext deleteObject:]' – TechZen

+0

當你使用一個名爲'addTypologyObject'的方法時,你期望發生什麼?我認爲你誤解了關於核心數據的一些重要問題。你提到的兩種方法都不像你認爲他們應該做的那樣。 – TechZen

相關問題