我是核心数据的新手。我想更新重复值。例如我的桌子看起来像这样
id | Name
============
1 | Joseph
2 | Fernandez
3 | Joseph
4 | James
假设我想将 id 1 和 4 对应的 Joseph 更新为“myName”。当我尝试更新它时,它只更新第 4 行。我在任何文档中都找不到任何方法来做到这一点。谁能建议我一个解决方案?
还有一个问题,如何打印所有名称值?
您必须阅读文档以了解如何更新记录 http://www.appcoda.com/core-data-tutorial-update-delete/
詹姆士,
我将尝试使用示例代码回答您的两个问题。
要更新特定对象,您需要NSFetchRequest
使用谓词设置新对象,获取对象(类型为NSManagedObject
),更新您感兴趣的值并保存上下文。
因此,例如:
NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"YourEntityName"];
// set the predicate (it's equal to set a WHERE SQL clause) filtering on the name for example
// use camel case notation if possible, so instead of Name use name (for this you have to changes your model, if you don't want to do it use Name)
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"name == %@", @"Joseph"]];
NSError* error = nil;
NSArray* results = [context executeFetchRequest:fetchRequest error:&error];
// do some error checking here...
for (NSManagedObject resultItem in results) {
// use KVC (for example) to access your object properties
[resultItem setValue:@"myName" forKey:@"name"];
}
// save your context here
// if you don't save, changes are not stored
要打印,您需要创建一个新的NSFetchRequest
,抓取对象(类型NSManagedObject
)并使用NSLog
.
例如:
NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"YourEntityName"];
NSError* error = nil;
NSArray* results = [context executeFetchRequest:fetchRequest error:&error];
// do some error checking here...
for (NSManagedObject resultItem in results) {
NSLog(@"%@", [resultItem valueForKey:@"name"]);
}
PS 我提供的代码非常简单,我用于特定值的谓词检查name
. 由于这可能容易出错,我会修改模型并为您需要使用的每个对象使用一种guid(我不知道 id 是否适用,但我会将其名称更改为另一个名称,例如userId
)。完成后,您可以对其进行检查。
希望有帮助。
It's as simple as retrieving the NSManagedObject
and changing the Name
property. You can retrieve the NSManagedObject
with a fetch request. Once you changed the property and you want to keep it changed even when you close the application you'll have to do a save
on the managedObjectContext
.
You'll have to read over the documentation to get up to speed on core data: http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/Articles/cdBasics.html#//apple_ref/doc/uid/TP40001650-TP1
Edit: just NSLog
whatever you want to know, for example log you fetch request results.