我有一个名为 的实体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" ?
}