0

我想知道如何以编程方式更新核心数据对象。该对象虽然是一个 NSSet。所以我可以用下面的方案来总结一下:

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

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

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

所以是的,它们正在被存储,但它也会创建空行(清除它们而不是删除/更新它们)。

任何帮助,将不胜感激。谢谢!

4

2 回答 2

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 机器上,所以我无法检查它。

于 2011-07-17T23:15:26.013 回答
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对象端设置是否使用 Core Data 为您生成的实现 (.m) 中的关系访问器方法:

[aProperty_has_typologyObject addPropertiesObject:aPropertyObject];

或者

[aProperty_has_typologyObject addPropertiesObjects:aSetOfPropertyObjects];

...你就完成了。

如果您必须手动管理所有对象关系,Core Data 将不会提供太多实用程序。

于 2011-07-18T17:45:02.803 回答