CoreData编辑/覆盖对象

Jos*_*ane 16 core-data objective-c uitextview ipad uisplitviewcontroller

我正在玩一个新项目,一个使用Core Data的拆分视图iPad应用程序,我很想知道,因为它非常清楚如何添加和删除项目.如果我要改变它来保存文本,那么该文本将显示在a中UITextView,如何编辑或覆盖CoreData中的对象?

因此,用户UITextView在他们离开时键入他们的音符,然后编辑并保存他们当前选择的音符(表格视图中的对象).

感谢任何帮助.

Mat*_*ick 33

您只需使用a请求现有对象NSFetchRequest,更改需要更新的任何字段(只需要一个简单的myObject.propertyName setter),然后对数据上下文执行保存操作.

编辑添加代码示例.我同意MCannon,Core Data绝对值得一读.

此代码假定您使用包含Core Data内容的模板创建项目,以便您的app委托具有托管对象上下文等.请注意,此处没有错误检查,这只是基本代码.

获取对象

// Retrieve the context
if (managedObjectContext == nil) {
    managedObjectContext = [(YourAppNameAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}

// Retrieve the entity from the local store -- much like a table in a database
NSEntityDescription *entity = [NSEntityDescription entityForName:@"YourEntityName" inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];

// Set the predicate -- much like a WHERE statement in a SQL database
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"YourIdentifyingObjectProperty == %@", yourIdentifyingQualifier];
[request setPredicate:predicate];

// Set the sorting -- mandatory, even if you're fetching a single record/object
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"yourIdentifyingQualifier" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release]; sortDescriptors = nil;
[sortDescriptor release]; sortDescriptor = nil;

// Request the data -- NOTE, this assumes only one match, that 
// yourIdentifyingQualifier is unique. It just grabs the first object in the array. 
YourEntityName *thisYourEntityName = [[managedObjectContext executeFetchRequest:request error:&error] objectAtIndex:0];
[request release]; request = nil;
Run Code Online (Sandbox Code Playgroud)

更新对象

thisYourEntityName.ExampleNSStringAttributeName = @"The new value";
thisYourEntityName.ExampleNSDateAttributeName = [NSDate date];
Run Code Online (Sandbox Code Playgroud)

保存更改

NSError *error;
[self.managedObjectContext save:&error];
Run Code Online (Sandbox Code Playgroud)

现在您的对象/行已更新.