【发布时间】:2015-10-27 10:41:07
【问题描述】:
我正在尝试将数据插入 coredata,但我收到了类似的错误,
CoreData:错误:(1555)唯一约束失败:ZSIDETABLENAME.Z_PK
场景:-
首先:从 appdelegate.m 我将数据从我的 SQL 文件复制到文档目录的 sql 文件。
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
NSString* from;
NSString* to;
NSArray* mainPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [mainPath objectAtIndex:0]; // Get documents folder
/*VoiceRecords.plist file*/
from=[[NSBundle mainBundle]pathForResource:@"News" ofType:@"sqlite"];
to=[documentsDirectory stringByAppendingPathComponent:@"News.sqlite"];
[[NSFileManager defaultManager]copyItemAtPath:from
toPath:to error:nil];
from=nil;
to=nil;
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"News.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
它工作正常。然后我试图将用户输入的 url 保存在 mainviewcontroller.m 的 coredata 中。
- (void)feedParserDidFinish:(MWFeedParser *)parser {
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"IWorld"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"feedurl = %@", self.Feedlink];
NSManagedObjectContext *context = [self managedObjectContext];
if ([[context executeFetchRequest:fetchRequest error:NULL] count] == 0) {
NSError *error = nil;
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"feedurl contains %@",check];
[fetchRequest setPredicate:predicate];
NSMutableArray *checkp = [[context executeFetchRequest:fetchRequest error:&error]mutableCopy];
if (checkp.count<=0) {
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"IWorld" inManagedObjectContext:context];
[newDevice setValue:self.Name forKey:@"name"];
[newDevice setValue:self.WebsiteName forKey:@"websitename"];
[newDevice setValue:self.Feedlink forKey:@"feedurl"];
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
//Save value in lockbox
NSArray *keys = [[[newDevice entity] attributesByName] allKeys];
NSDictionary *dict = [newDevice dictionaryWithValuesForKeys:keys];
}
}
NSFetchRequest *fetchrequestforside=[NSFetchRequest fetchRequestWithEntityName:@"Sidetablename"]; //Sidetablename is entity
fetchrequestforside.predicate=[NSPredicate predicateWithFormat:@"feedurl = %@", self.Feedlink];
NSManagedObjectContext *context = [self managedObjectContext];
if ([[context executeFetchRequest:fetchrequestforside error:NULL] count] == 0) {
// Create a new managed object
NSError *error = nil;
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"feedurl contains %@",check ]; //check is urlstring
[fetchrequestforside setPredicate:predicate];
NSMutableArray *checkp = [[context executeFetchRequest:fetchrequestforside error:&error]mutableCopy];
if (checkp.count<=0) //if coredata will find url then notstore in coredata else stored procedure
{
NSManagedObject *newDevice1 = [NSEntityDescription insertNewObjectForEntityForName:@"Sidetablename" inManagedObjectContext:context];
if (self.Name)
{
[newDevice1 setValue:self.Name forKey:@"name"];
}
if (self.WebsiteName)
{
[newDevice1 setValue:self.WebsiteName forKey:@"websitename"];
}
if (self.Feedlink)
{
[newDevice1 setValue:self.Feedlink forKey:@"feedurl"];
}
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]); // Getting error here through nslog //CoreData: error: (1555) UNIQUE constraint failed: ZSIDETABLENAME.Z_PK
}
注意:这一切都是第一次发生。第二次我将运行应用程序时一切正常。不知道问题出在哪里?
【问题讨论】:
-
根据错误消息,您已将属性 sidetablename 设置为唯一,并且您正在尝试为属性 sidetablename 保存另一个具有相同值的对象。您是否已通过调试器查看您尝试保存的对象中的内容以及实际核心数据数据库中的内容?您在尝试自我诊断问题时做了什么?这些测试的结果是什么?在调试器中单步执行时您看到了什么?
-
您是如何创建要复制的 SQLite 文件的?
-
@TomHarrington 先生,我从文档目录中获取了 sql 文件,我在其中输入了静态数据,然后将其复制到包中,然后在应用程序第一次启动时复制数据。
-
@JodyHagins 是的,先生,我已经用调试器试过了。数据不存储在 sqlfile 中。因为当调试器运行
if (![context save:&error])这种方法时,我在 nslog 中遇到错误。但我可以通过获取请求来获取它。但是当应用程序再次启动时,所有数据都丢失了。
标签: ios objective-c core-data