I am working on a coredata project in xcode 4.3 for ios 5.1. I created an empty ARC project with the CoreData checkbox selected, following the add by xcode methods to control the model and change me according to the guide for copying preopulate sqllite db to my application, prepulate db is in the resource group inside the project folder and has the same thing name of model and project.
- (void)saveContext { NSError *error = nil; NSManagedObjectContext *managedObjectContext = self.managedObjectContext; if (managedObjectContext != nil) { if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
here instead of implementing a viewcontroller with some field for interacting with 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 arise when I try to see the records stored inside the db, actually the error of pressing a button with the name "Elenca", xcode gives me this error:
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 also tried 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
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, entity name (null), properties {\ n miracoli = \" (), name miracoli, isOptional 1, isTransient 0, entity Meco, renamingIdentifier miracoli, check predicates (\ n), warnings (\ n), versionHashModifier (null) \ n userInfo {\ n}, attributeType 700, attributeValueClassName NSString, defaultValue (null) \ "; \ n morte = \" (), name morte, isOptional 1, isTransient 0, Meco object, renamingIdentifier morte, check predicates (\ n), warnings (\ n), versionHashModifier (null) \ n userInfo {\ n }, attributeType 700, attributeValueClassName NSString, defaultValue (null) \ "; \ n nome = \" (), name nome, isOptional 1, isTransient 0, Meco object, renamingIdentifier nome, check predicates (\ n), warnings (\ n), versionHashModifier (null) \ n userInfo {\ n}, attributeType 700, attributeValueClassName NSString, defaultValue (null) \ "; \ n relationship = \" (), name relationship, isOptional 1, isTrans ient 0, Meco entity, renamingIdentifier relationships, validation predicates (\ n) , warnings (\ n), versionHashModifier (null) \ n userInfo {\ n}, target entity Stica, relation inverseRelationship, minCount 1, maxCount 1, isOrdered 0, deleteRule 1 \ "; \ n}, entities (null), userInfo {\ n}, versionHashModifier (null) "; Stica = "() name Stica, managedObjectClassName NSManagedObject, renamingIdentifier Stica, isAbstract 0, entity 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, Stica object, renamingIdentifier relationships, validation predicates (\ n), warnings (\ n), versionHashModifier (null) \ n userInfo {\ n}, Meco target, inverseRelationship relationship, minCount 1, maxCount 1, isOrdered 0, deleteRule 1 \ "; \ n sfiga = \" (), name sfiga, isOptional 1, isTransient 0, Stica object, renamingIdentifier sfiga, check predicates (\ n), warnings (\ n), versionHashModifier (null) \ n userInfo {\ n}, attributeType 700, attributeValueClassName NSString, defaultValue (null) \ "; \ n}, subentiti es (null), userInfo {\ n}, versionHashModifier (null) "; }, fetch request patterns {}
and I donβt know why storeURL has this form, what is βfile: // localhost /β at the end of the line? Why can't create a .sqlite file? and which is the right way to solve the problem? I already tried resetting the simulator and the paths are correct ...
Thank you in advance
edit1: tut i learned, this
edit2: A possible solution that works is to change this piece of code:
NSString *storePath = [[[self applicationDocumentsDirectory] absoluteString] stringByAppendingPathComponent:@"Prova1.sqlite"]; NSURL *storeURL = [NSURL fileURLWithPath:storePath];
with:
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Prova1.sqlite"];