У меня есть сложный вопрос, на мой взгляд.Редактировать объект CoreData, а затем сохранить контекст
У меня есть две сущности, одна называется InProject
, которая имеет вечные атрибуты и одно отношение. отношения с другим лицом, которое называется Ins
.
Я редактирую один из Ins
, что связано с InProject
. Я использовал InProject
атрибут ID
, который затем возвращает значение NSDictionary, которое имеет несколько ключевых значений, один из которых для массива Ins
. Затем я нахожу Ins, мне нужно редактировать в цикле for, я их редактирую, но затем я становлюсь неуклюжим, потому что я не уверен, как сохранить contect InProject с обновленным Ins
Я хотел бы помочь код, который я сделал ниже, чтобы выяснить, как сохранить InProject
после того, как я перезаписал атрибуты Ins
, которые мне нужно обновить.
Это то, что мой код выглядит после недели стоит того, чтобы бороться с этой проблемой .. :(
- (void)editSelectedins:(NSString *)projIDString UpdatedNSD:(NSMutableDictionary *)updatedNSD DPC:(int)dpc{
// get context
NSManagedObjectContext *context = [self managedObjectContext];
if (context == nil) {
NSLog(@"Nil");
}
else {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"InsProject" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
NSMutableArray *InsProjectDictionaryArray = [[NSMutableArray alloc] init];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (InsProject *insProj in fetchedObjects) {
NSMutableDictionary *tempInsProjectDictionaryArray = [[ NSMutableDictionary alloc] init];
[tempInsProjectDictionaryArray setObject:insProj.companyName forKey:@"CompanyName"];
[tempInsProjectDictionaryArray setObject:insProj.projNo forKey:@"ProjNo"];
[tempInsProjectDictionaryArray setObject:insProj.desc forKey:@"Desc"];
[tempInsProjectDictionaryArray setObject:insProj.guid forKey:@"GUID"];
[tempInsProjectDictionaryArray setObject:insProj.projID forKey:@"ProjID"];
[tempInsProjectDictionaryArray setObject:insProj.ins forKey:@"ins"];
[InsProjectDictionaryArray addObject:tempInsProjectDictionaryArray];
}
// now that you have the InsProjects, choose the one you are curently working on in insView using the projectID
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ProjID==%@",projIDString];
[fetchRequest setPredicate:predicate];
// new array with one value that was created using the NSPredicate ProjID
NSArray *tempInsProjectArray = [InsProjectDictionaryArray filteredArrayUsingPredicate:predicate];
// get ins array out of the NSDictionary to edit
NSSet *inssForInsProject = tempInsProjectArray[0][@"ins"];
NSMutableArray *tempAllinss = [[NSMutableArray alloc] init]; // this will contain everything, that means all repeated values are included
for (Items* currItem in [inssForInsProject allObjects]) {
NSArray *keys = [[[currItem entity] attributesByName] allKeys];
NSDictionary *dict = [currItem dictionaryWithValuesForKeys:keys];
[tempAllinss addObject:dict];
}
NSArray *myArray = [tempAllinss copy];
// get the correct items from myArray anything whos dpc matches the dpc parameter of this method
NSMutableArray *editedinsArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [myArray count]; i++) {
NSMutableDictionary *tempinssDictionary = [myArray objectAtIndex:i];
// if you get a match put it into the new editedinsArray to be edited
if ([[tempinssDictionary objectForKey:@"dpc"] integerValue] == dpc) {
[editedinsArray addObject:tempinssDictionary];
}
}
// by now you should have three things
// 1, access to your ins coredata object //this s wrong I actually have access to insProject
// 2, the values you need to be edited saved into a NSArray (editedinsArray, which will be used to check against and keep old values correct)
// 3, UpdatedNSD which will be used to update any values that need to be updated.
// go through your values and update the ins object
int i = 0;
for (ins *temp in editedinsArray) {
NSDictionary *currentEditedins = [editedinsArray objectAtIndex:i];
i++;
// these values should stay the same so use currentEditedins which contains old vals
NSString *stringToNumberDpc = [currentEditedins valueForKey:@"dpc"];
int tempDpcNum = [stringToNumberDpc integerValue];
NSNumber *dpcNumber = [NSNumber numberWithInt:tempDpcNum];
temp.dpc = dpcNumber;
NSString *totDQtyString = [currentEditedins valueForKey:@"totDQty"];
if ((NSNull *)totDQtyString == [NSNull null]) {
temp.totDQty = @"";
} else {
temp.totDQty = totDQtyString;
}
NSString *totShipString = [currentEditedins valueForKey:@"totShip"];
if ((NSNull *)totShipString == [NSNull null]) {
temp.totShip = @"";
} else {
temp.totShip = totShipString;
}
// values to be updated so use updatedNSD wthich was passed in as method param with the new vals
temp.newInsComp = [updatedNSD valueForKey:@"newInsComp"];
temp.newDryComp = [updatedNSD valueForKey:@"newDryComp"];
temp.updatedRow = [updatedNSD valueForKey:@"updatedRow"];
}
#warning --- I have no idea what to do here... i.e. how do I update the tempInsProjectArray.ins values I have just updated in the above for loop then save context which I hope would update insProj and the ins entities involved.
//save
[context save:&error];
}
}
любая помощь будет массово оценили. Как вы можете видеть в нижней части кода с #warning Я объясняю, где у меня проблема. Если я запишу temp внутри цикла for, я вижу, что обновленные значения отлично имеют проблему, с которой я сталкиваюсь, - как мне затем обновлять текущие значения tempInsProjectArray.ins, которые я только что редактировал, а затем сохранить их
Надеюсь, что я предоставил вам достаточно информации, чтобы описать сложный вопрос, но я надеюсь, что кто-то там шляпа может помочь.
Мунди, большое спасибо за то, что нашли время, чтобы ответить мне. Я распечатал ваши предложения и буду следить за тем, чтобы я теперь лучше справлялся с правилами, которые вы указали. Я думаю, что, возможно, проблема усугубляет качество моего кода, поскольку я как бы уловил попытку добиться чего-то, чего я не знал о том, как добиться успеха. (если это имеет смысл) в любом случае. Я собираюсь дать вам ответ. Я отправлю обратно с моими результатами.еще раз большое спасибо за ответ и время, чтобы прочитать мой вопрос. – HurkNburkS
Im в настоящее время работает через него, но я получаю сообщение об ошибке, когда поток попадает в строку, в которой вы объявляете объекты NSArray. это ошибка, которую я получаю «Завершение приложения из-за неперехваченного исключения» NSInvalidArgumentException », причина:« keypath projectID не найден в объекте » –
HurkNburkS
Проверьте имена атрибутов как в подклассах управляемого объекта, так и в объекте модель. Эта ошибка достаточно ясна, вы могли бы понять это. – Mundi