我有一个名为Attribute
的实体,它有2个属性attribute_name
和attribute_value
。
此Attribute
entity
与另一个名为Project
的实体存在多对多关系。
我希望像所有attribute_name
一样插入它,使一个项目相同,只有attribute_value
不同。
当我输入数据时,我会将Attribute
实体的这些属性放在两个不同的数组中,然后使用Save
循环将其保存到for
按钮中。
为了保持attribute_name
不同,我检查它们是否已经存在于数据库中,如果是,那么我只保存attribute_value
。
但它仍然将“attributes_name”作为NULL
插入。正在为attributes_name
保存数据。
所以,当我第二次点击“保存”按钮时,我得到的文本字段比以前加倍。这是空的。
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Attributes" inManagedObjectContext:self.context]];
[request setPredicate:[NSPredicate predicateWithFormat:@"attribute_name in %@", applicationDelegate.attributesTextArray]];
NSError * error;
NSArray * anArray = [context executeFetchRequest:request error:&error];
for (int i = 0; i < [applicationDelegate.attributesTextArray count]; i++) {
attributesObject = (Attributes*)[NSEntityDescription insertNewObjectForEntityForName:@"Attributes" inManagedObjectContext:self.context];
if (anArray.count == 0) {
attributesObject.attribute_name = [applicationDelegate.attributesTextArray objectAtIndex:i];
attributesObject.attribute_value = [applicationDelegate.attributeGradesArray objectAtIndex:i];
} else {
attributesObject.attribute_value = [applicationDelegate.attributeGradesArray objectAtIndex:i];
}
[testArray addObject:attributesObject];
}
for (int o=0; o<[testArray count]; o++) {
NSData * retrievedData = [[NSUserDefaults standardUserDefaults] objectForKey:@"ProjectManagedObject"];
NSURL * retrievedUrl = [NSKeyedUnarchiver unarchiveObjectWithData:retrievedData];
NSManagedObjectID * projectObjectId = [applicationDelegate.persistentStoreCoordinator managedObjectIDForURIRepresentation:retrievedUrl];
projectObject = (Project*)[applicationDelegate.managedObjectContext objectWithID:projectObjectId];
[projectObject addAttributesObject:[testArray objectAtIndex:o]];
NSError * error;
if (![context save:&error]) {
NSLog(@"UNABLE TO SAVE DATA: %@", [error userInfo]);
}
这到底出了什么问题?
更新:
NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription * entity = [NSEntityDescription entityForName:@"Project" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError * error;
NSArray * fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
NSLog(@"OBJECT FETCHED:%d", [fetchedObjects count]);
if (fetchedObjects.count != 0) {
Project * project_ = [fetchedObjects objectAtIndex:applicationDelegate.projectNumber];
NSArray * saved_attributes = [project_.attributes allObjects];
if (saved_attributes.count != 0) {
//Update "attribute-value"
} else {
// create new attribute and insert both "attribute_name" and "attribute_value" ?
}
答案 0 :(得分:0)
你的行
attributesObject = (Attributes*)[NSEntityDescription insertNewObjectForEntityForName:@"Attributes" inManagedObjectContext:self.context];
创建 new “Attributes”对象,与对象是否匹配无关 之前是否找到了名称。如果要更新现有对象,则必须 设置获取对象的属性,而不是创建新对象。