Select "Core Data" checkbox
".xcdatamodeld" file created in project
select data model file, "Add Entity" at bottom left corner
"Add attributes" using the "+" sign
File > New File > Core Data > NSManagedObject
Select data model, and entity to create the NS managed object
.h and .m created in project
File > New File > UIViewController
AppDelegate.h (add View controller )
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
// ADDED
StartVC *vc = [[StartVC alloc] initWithNibName:@"StartVC" bundle:nil];
// ADDED
self.window.rootViewController = vc;
// ADDED
[vc release];
[self.window makeKeyAndVisible];
return YES;
}
VC .m
for adding/inserting data
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
AppDelegate *ad = [[UIApplication sharedApplication] delegate];
Property *prop = (Property *)[NSEntityDescription insertNewObjectForEntityForName:@"Property" inManagedObjectContext:ad.managedObjectContext];
prop.name = @"Sengkang";
prop.seller = @"Beng";
prop.price = (NSDecimalNumber *)[NSDecimalNumber numberWithInt: 100000];
prop.address = @"123, Anchorvale #01-01";
NSError *err;
if(![ad.managedObjectContext save:&err])
NSLog(@"error %@", [err domain]);
else
NSLog(@"Data added");
}
for reading data
// reading
NSEntityDescription *desc = [NSEntityDescription entityForName:@"Property" inManagedObjectContext:ad.managedObjectContext];
NSFetchRequest *req = [[NSFetchRequest alloc] init];
[req setEntity:desc];
NSArray *obj = [ad.managedObjectContext executeFetchRequest:req error:&err];
for(Property *p in obj)
{
NSLog(@"-------------");
NSLog(@"Property name: %@", p.name);
NSLog(@"Price: %f", p.price.floatValue);
NSLog(@"Seller: %@", p.seller);
}
No comments:
Post a Comment