Im using xcode 4 and i've created a CoreData model. I would like to know if its possible to insert data into an entity within xcode.
Please don't 开发者_如何学Pythontell me the only way to enter data into a model is programmatically.
Cheers
Ray Wenderlich provides a tutorial on How to Preload/Import Existing Data using a Python script to populate the database.
His three-part series on Core Data is very informative.
You can not enter data directly with XCode. If you don't want to do this with code you can prepopulate your db. Have a look at this Q&A on SO.
It's a very slow procedure, but you can populate Core Data.
Insert the following code in appDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
...
//test
//writing data
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *model = [NSEntityDescription insertNewObjectForEntityForName:@"Invitados" inManagedObjectContext:context];
[model setValue:@"Alicia" forKey:@"name"];
[model setValue:@"Sanchez" forKey:@"firstname"];
[model setValue:@"Romero" forKey:@"secondname"];
NSError *error;
if (![context save:&error]) {
NSLog(@"Couldn't save: %@", [error localizedDescription]);
}
//retrieving data
// NSManagedObjectContext *context = [self managedObjectContext];
//NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Invitados" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *get in fetchedObjects) {
NSLog(@"Nombre: %@", [get valueForKey:@"name"]);
NSLog(@"Apellido 1: %@", [get valueForKey:@"firstname"]);
NSLog(@"Apellido 2: %@",[get valueForKey:@"secondname"]);
}
// End test
精彩评论