2010-11-27 71 views
16

我正在玩一个新项目,使用核心数据的拆分视图iPad应用程序,我想知道,因为它很清楚如何添加和删除项目。如果我是说改变这种包含文本,则该文本在UITextView显示,我怎么能编辑或CoreData覆盖的对象?CoreData编辑/覆盖对象

所以用户键入其在UITextView,离开时,它编辑并保存(在表格视图对象)的说明他们当前选择的音符。

得到任何帮助的感谢。

回答

33

只需请求用一个NSFetchRequest,改变什么领域需要进行更新(简单myObject.propertyName二传手是所有的需要)现有的对象,然后执行保存的数据上下文动作。

EDIT添加代码的例子。我同意MCannon,Core Data绝对值得一读。

此代码假定您使用包括核心数据的东西,这样你的应用程序委托有一个管理对象上下文,等等。注意,没有错误检查这里的模板创建的项目,这仅仅是基本的代码。

抓取物体

// 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; 

更新对象

thisYourEntityName.ExampleNSStringAttributeName = @"The new value"; 
thisYourEntityName.ExampleNSDateAttributeName = [NSDate date]; 

保存更改

NSError *error; 
[self.managedObjectContext save:&error]; 

现在你的对象/行被更新了。

+0

好的,你能指点一下或者做一点代码示例吗?对不起,我对CoreData相当陌生,有一个示例会帮助我理解。 – 2010-11-27 20:28:18

+1

我编辑我的答案,包括一些基本的代码。 – 2010-11-28 10:15:47