简体   繁体   English

该操作无法完成。 (可可错误512.)Coredata Iphone。 没有文件可以复制到文档文件夹中

[英]The operation couldn’t be completed. (Cocoa error 512.) Coredata Iphone. No files can be copied in documents folder

I'm working on a coredata project in a xcode 4.3 version for ios 5.1. 我正在为ios 5.1的xcode 4.3版本中的coredata项目工作。 I've made an ARC empty project with CoreData checkbox selected, following the methods add by xcode to manage model and modified by me following a tutorial for copying a prepopulate sqllite db to my app, the prepopulate db is in the resource group inside project folder and has the same name of model and project. 我已经选择了CoreData复选框的ARC空项目,按照xcode添加的方法来管理模型,并按照我的教程将preopulate sqllite数据库复制到我的应用程序,预填充数据库位于项目文件夹内的资源组中并且具有相同的模型和项目名称。

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&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. 
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
         } 
     }
}

#pragma mark - Core Data stack

// Returns the managed object context for the application.

// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.

- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
         return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.

- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Prova1" withExtension:@"momd"];

NSLog(@"modelURL %@",modelURL);

    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

NSString *storePath = [[[self applicationDocumentsDirectory] absoluteString] stringByAppendingPathComponent:@"Prova1.sqlite"];
 NSLog(@"storePath %@",storePath);

 NSURL *storeURL = [NSURL fileURLWithPath:storePath];
 NSLog(@"storeURL %@",storeURL);

 // Put down default db if it doesn't already exist
 NSFileManager *fileManager = [NSFileManager defaultManager];
 if (![fileManager fileExistsAtPath:storePath]) {
     NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Prova1" ofType:@"sqlite"];
     if (defaultStorePath) {
          [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
     }
}/**/

/*NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Prova1.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;
}

#pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.

- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

here instead the viewcontroller's implementation with some field to interact with db. 相反,viewcontroller的实现与一些字段与db交互。

@implementation ALCViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.textfied1 = [[UITextField alloc] initWithFrame:CGRectMake(200, 50, 300, 30)];
    self.textfied1.borderStyle = UITextBorderStyleRoundedRect;
    self.textfied1.delegate = self;
    [self.view addSubview:self.textfied1];

    self.textfied2 = [[UITextField alloc] initWithFrame:CGRectMake(200, 100, 300, 30)];
    self.textfied2.borderStyle = UITextBorderStyleRoundedRect;
    self.textfied2.delegate = self;
    [self.view addSubview:self.textfied2];

    self.salvaButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.salvaButton setFrame:CGRectMake(200, 150, 100, 20)];
    [self.salvaButton setTitle:@"salva" forState:UIControlStateNormal];
    [self.salvaButton addTarget:self action:@selector(salva:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:self.salvaButton];

    self.cercaButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.cercaButton setFrame:CGRectMake(200, 200, 100, 20)];
    [self.cercaButton setTitle:@"Elenca" forState:UIControlStateNormal];
    [self.cercaButton addTarget:self action:@selector(cerca:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:self.cercaButton];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIToolbar *toolbar = [[UIToolbar alloc] init];
    [toolbar setBarStyle:UIBarStyleBlackTranslucent];
    [toolbar sizeToFit];
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneClicked:)];

    if ([textField isEqual:self.textfied1]) {
        [doneButton setTag:1];
    }
    if ([textField isEqual:self.textfied2]) {
        [doneButton setTag:2];
    }

    [toolbar setItems:[NSArray arrayWithObjects:/*flexibleSpaceLeft,*/ doneButton, nil]];
    [textField setInputAccessoryView:toolbar];
    [textField setText:@""];
    [textField setTextColor:[UIColor blackColor]];
    [textField setFont:[UIFont systemFontOfSize:16]];/**/
    return YES;
}

- (void)doneClicked:(id)sender {
    UIButton *bSender = (UIButton *)sender;

    switch ([bSender tag]) {
    case 1: {
        [self.textfied1 resignFirstResponder];
    }
    break;
    case 2: {
        [self.textfied2 resignFirstResponder];
    }
    break;
    default:
    break;
    }
}

- (void)salva:(id)sender {
    ALCAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [appDelegate managedObjectContext];

    NSManagedObject *newContact;
    newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Stica" inManagedObjectContext:context];
    [newContact setValue:self.textfied1.text forKey:@"nome"];
    [newContact setValue:self.textfied2.text forKey:@"sfiga"];

    self.textfied1.text = @"";
    self.textfied2.text = @"";

    NSError *error;
    [context save:&error];
    //status.text = @”Contact saved”;
}

- (void)cerca:(id)sender {
    ALCAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Stica" inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDesc];

    /*NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name = %@)", name.text];
 [request setPredicate:pred];*/

    NSError *error;

    NSArray *objects = [context executeFetchRequest:request error:&error];

    if ([objects count] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Risultati" message:@"Vuoto" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
    } 
    else {
        for (NSManagedObject *object in objects) {
            NSMutableString *string = [[NSMutableString alloc] initWithFormat:@"%@ - %@",[object valueForKey:@"nome"],[object valueForKey:@"sfiga"]];
            NSLog(@"%@",string);
        }
    }
}

@end

The problems come when i try to see the records stored inside the db, in fact the error pushing the button named "Elenca", xcode give me this error: 当我试图看到存储在db中的记录时出现问题,实际上错误按下了名为“Elenca”的按钮,xcode给了我这个错误:

Unresolved error Error Domain=NSCocoaErrorDomain Code=512 
"The operation couldn’t be completed. (Cocoa error 512.)" 
UserInfo=0x6e7a120 {
    reason=Failed to create file; code = 2
}, 
{
    reason = "Failed to create file; code = 2";
}

I've tried also to output some variables: 我也试过输出一些变量:

storePath file:/localhost/Users/winimac01/Library/Application%20Support/iPhone%20Simulator/5.1/Applications/7733DC6C-CE52-4EB4-9A60-26962F7AEDD9/Documents/Prova1.sqlite storePath文件:/localhost/Users/winimac01/Library/Application%20Support/iPhone%20Simulator/5.1/Applications/7733DC6C-CE52-4EB4-9A60-26962F7AEDD9/Documents/Prova1.sqlite

storeURL file:/localhost/Users/winimac01/Library/Application%2520Support/iPhone%2520Simulator/5.1/Applications/7733DC6C-CE52-4EB4-9A60-26962F7AEDD9/Documents/Prova1.sqlite -- file://localhost/ storeURL文件:/localhost/Users/winimac01/Library/Application%2520Support/iPhone%2520Simulator/5.1/Applications/7733DC6C-CE52-4EB4-9A60-26962F7AEDD9/Documents/Prova1.sqlite - file:// localhost /

modelURL file://localhost/Users/winimac01/Library/Application%20Support/iPhone%20Simulator/5.1/Applications/7733DC6C-CE52-4EB4-9A60-26962F7AEDD9/Prova1.app/Prova1.momd/ 2012-10-22 12:30:46.598 Prova1[2479:fb03] () isEditable 0, entities { Meco = "() name Meco, managedObjectClassName NSManagedObject, renamingIdentifier Meco, isAbstract 0, superentity name (null), properties {\\n miracoli = \\"(), name miracoli, isOptional 1, isTransient 0, entity Meco, renamingIdentifier miracoli, validation predicates (\\n), warnings (\\n), versionHashModifier (null)\\n userInfo {\\n}, attributeType 700 , attributeValueClassName NSString, defaultValue (null)\\";\\n morte = \\"(), name morte, isOptional 1, isTransient 0, entity Meco, renamingIdentifier morte, validation predicates (\\n), warnings (\\n), versionHashModifier (null)\\n userInfo {\\n}, attributeType 700 , attributeValueClassName NSString, defaultValue (null)\\";\\n nome = \\"(), name nome, isOptional 1, isTransient 0, entity Meco, renamingIdentifier nome, modelURL文件://localhost/Users/winimac01/Library/Application%20Support/iPhone%20Simulator/5.1/Applications/7733DC6C-CE52-4EB4-9A60-26962F7AEDD9/Prova1.app/Prova1.momd/ 2012-10-22 12: 30:46.598 Prova1 [2479:fb03]()isEditable 0,entities {Meco =“()名称Meco,managedObjectClassName NSManagedObject,renamingIdentifier Meco,isAbstract 0,superentity name(null),properties {\\ n miracoli = \\”(),名称miracoli,isOptional 1,isTransient 0,实体Meco,renamingIdentifier miracoli,验证谓词(\\ n),警告(\\ n),versionHashModifier(null)\\ n userInfo {\\ n},attributeType 700,attributeValueClassName NSString,defaultValue(null) \\“; \\ n morte = \\”(),名称为morte,isOptional 1,isTransient 0,实体Meco,renamingIdentifier morte,验证谓词(\\ n),警告(\\ n),versionHashModifier(null)\\ n userInfo {\\ n },attributeType 700,attributeValueClassName NSString,defaultValue(null)\\“; \\ n nome = \\”(),name nome,isOptional 1,isTransient 0,entity Meco,renamingIdentifier nome, validation predicates (\\n), warnings (\\n), versionHashModifier (null)\\n userInfo {\\n}, attributeType 700 , attributeValueClassName NSString, defaultValue (null)\\";\\n relationship = \\"(), name relationship, isOptional 1, isTransient 0, entity Meco, renamingIdentifier relationship, validation predicates (\\n), warnings (\\n), versionHashModifier (null)\\n userInfo {\\n}, destination entity Stica, inverseRelationship relationship, minCount 1, maxCount 1, isOrdered 0, deleteRule 1\\";\\n}, subentities (null), userInfo {\\n}, versionHashModifier (null)"; 验证谓词(\\ n),警告(\\ n),versionHashModifier(null)\\ n userInfo {\\ n},attributeType 700,attributeValueClassName NSString,defaultValue(null)\\“; \\ n relationship = \\”(),名称关系, isOptional 1,isTransient 0,实体Meco,renamingIdentifier关系,验证谓词(\\ n),警告(\\ n),versionHashModifier(null)\\ n userInfo {\\ n},目标实体Stica,inverseRelationship relationship,minCount 1,maxCount 1, isOrdered 0,deleteRule 1 \\“; \\ n},subentities(null),userInfo {\\ n},versionHashModifier(null)”; Stica = "() name Stica, managedObjectClassName NSManagedObject, renamingIdentifier Stica, isAbstract 0, superentity name (null), properties {\\n nome = \\"(), name nome, isOptional 1, isTransient 0, entity Stica, renamingIdentifier nome, validation predicates (\\n), warnings (\\n), versionHashModifier (null)\\n userInfo {\\n}, attributeType 700 , attributeValueClassName NSString, defaultValue (null)\\";\\n relationship = \\"(), name relationship, isOptional 1, isTransient 0, entity Stica, renamingIdentifier relationship, validation predicates (\\n), warnings (\\n), versionHashModifier (null)\\n userInfo {\\n}, destination entity Meco, inverseRelationship relationship, minCount 1, maxCount 1, isOrdered 0, deleteRule 1\\";\\n sfiga = \\"(), name sfiga, isOptional 1, isTransient 0, entity Stica, renamingIdentifier sfiga, validation predicates (\\n), warnings (\\n), versionHashModifier (null)\\n userInfo {\\n}, attributeType 700 , attributeValueClassName NSString, defaultValue (null)\\";\\n}, subentities (null) Stica =“()名称Stica,managedObjectClassName NSManagedObject,renamingIdentifier Stica,isAbstract 0,superentity name(null),properties {\\ n nome = \\”(),name nome,isOptional 1,isTransient 0,entity Stica,renamingIdentifier nome,validation谓词(\\ n),警告(\\ n),versionHashModifier(null)\\ n userInfo {\\ n},attributeType 700,attributeValueClassName NSString,defaultValue(null)\\“; \\ n relationship = \\”(),名称关系,isOptional 1,isTransient 0,实体Stica,renamingIdentifier关系,验证谓词(\\ n),警告(\\ n),versionHashModifier(null)\\ n userInfo {\\ n},目标实体Meco,inverseRelationship relationship,minCount 1,maxCount 1,isOrdered 0,deleteRule 1 \\“; \\ n sfiga = \\”(),名称sfiga,isOptional 1,isTransient 0,实体Stica,renamingIdentifier sfiga,验证谓词(\\ n),警告(\\ n),versionHashModifier(null)\\ n userInfo {\\ n},attributeType 700,attributeValueClassName NSString,defaultValue(null)\\“; \\ n},子实体(null) , userInfo {\\n}, versionHashModifier (null)"; ,userInfo {\\ n},versionHashModifier(null)“; }, fetch request templates { } },获取请求模板{}

and I don't know why storeURL has that form, what is the " -- file://localhost/" ath the end of the string? 我不知道为什么storeURL有这种形式,字符串末尾的“ - file:// localhost /”是什么? Why can't create the .sqlite file? 为什么不能创建.sqlite文件? and wich is the right way to fix the problem? 这是解决问题的正确方法吗? I've already tried to reset the simulator and the paths are correct... 我已经尝试重置模拟器,路径正确...

Thanks in advance 提前致谢

edit1: the tut that i've studied is this edit1:我研究过的啧啧就是这个

edit2: A possible solution that works is change this piece of code: edit2:一个可行的解决方案是改变这段代码:

NSString *storePath = [[[self applicationDocumentsDirectory] absoluteString] stringByAppendingPathComponent:@"Prova1.sqlite"];
NSURL *storeURL = [NSURL fileURLWithPath:storePath];

 // Put down default db if it doesn't already exist
 NSFileManager *fileManager = [NSFileManager defaultManager];
 if (![fileManager fileExistsAtPath:storePath]) {
     NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Prova1" ofType:@"sqlite"];

     if (defaultStorePath) {
         [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
     }
 }/**/

with: 有:

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Prova1.sqlite"];

// Put down default db if it doesn't already exist
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:storePath]) {
    NSURL *defaultStoreURL = [[NSBundle mainBundle] URLForResource:@"Prova1" withExtension:@"sqlite"];

    if (defaultStoreURL) {
        [fileManager copyItemAtURL:defaultStoreURL toURL:storeURL error:NULL];
    }
}/**/

The usage of absoluteString in absoluteString的用法

NSString *storePath = [[[self applicationDocumentsDirectory] absoluteString] stringByAppendingPathComponent:@"Prova1.sqlite"];

is not correct. 是不正确的。 It creates a string 它创建一个字符串

file:/localhost/Users/winimac01/...

where "file:" is actually part of the string, so this file surely does not exist. 其中“file:”实际上是字符串的一部分,所以这个文件肯定不存在。

Using path instead should fix the problem: 使用path应该解决问题:

NSString *storePath = [[[self applicationDocumentsDirectory] path] stringByAppendingPathComponent:@"Prova1.sqlite"];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Error Domain = NSCocoaErrorDomain代码= 512“该操作无法完成。该操作无法完成。是一个目录 - Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed.The operation couldn’t be completed. Is a directory 该操作无法完成。 (可可错误-1。) - PHPhotoLibrary - The operation couldn’t be completed. (Cocoa error -1.) - PHPhotoLibrary 该操作无法完成。 (可可错误133021.)+迅捷2 - The operation couldn’t be completed. (Cocoa error 133021.) + swift 2 该操作无法完成。 (可可错误1560.) - The operation couldn’t be completed. (Cocoa error 1560.) Phonegap,可可错误257-操作无法完成。 不允许操作 - Phonegap, Cocoa error 257 - The operation couldn’t be completed. Operation not permitted 如何解决错误:操作无法完成。 (可可错误3840。)json iOS? - How to resolve error:the operation couldn’t be completed. (cocoa error 3840.) json iOS? 无法保存到数据存储:无法完成操作。 (可可错误133020.) - Failed to save to data store: The operation couldn’t be completed. (Cocoa error 133020.) 该操作无法完成。 (可可错误3840。)”(在字符16周围的对象中没有键值。) - The operation couldn’t be completed. (Cocoa error 3840.)" (No value for key in object around character 16.) checkResourceIsReachableAndReturnError总是返回Domain = NSCocoaErrorDomain Code = 4“操作无法完成。 (可可错误4。)” - checkResourceIsReachableAndReturnError always return Domain=NSCocoaErrorDomain Code=4 “The operation couldn’t be completed. (Cocoa error 4.)” 将视频保存到我的相机胶卷中会返回错误:无法完成该操作。 (可可错误-1。) - Saving a video to my camera roll returns error: The operation couldn’t be completed. (Cocoa error -1.)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM