Thursday, July 21, 2011

Core data Basics -Part 1

Welcome to the world of core data
________________________________________

step 1) import core data framework

step 2) create a coredata object -> Test.xcdatamodeld
create entity -> Class
Create Attributes-> Name , Descrioptin;

step3) in AppDelegate class add these

NSManagedObjectContext *managedObjectContext_;
NSManagedObjectModel *managedObjectModel_;
NSPersistentStoreCoordinator *persistentStoreCoordinator_;


@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory;
- (void)saveContext;


###################################################

______________ in App delegate.m____________________________


#pragma mark -
#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_;
}
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"Test" ofType:@"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
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_;
}

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

NSError *error = nil;
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}

return persistentStoreCoordinator_;
}


#pragma mark -
#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];
}







#################################

_______________ in VeiwControll.h___

step5) create text fields to enter user values
UITextField* nameTextField;
UITextField* descriptionTextField;
UITextView* ingredientsTextView;
}
@property (nonatomic,retain) IBOutlet UITextField* nameTextField;
@property (nonatomic,retain) IBOutlet UITextField* descriptionTextField;
@property (nonatomic,retain) IBOutlet UITextView* ingredientsTextView;



##################

_______________in VC.m_____________


step6) to save the data in Sqlite


- (IBAction)save:(id)sender {

CoreData_rahul_saveDataAppDelegate* delegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext* managedObjectContext = delegate.managedObjectContext;

NSManagedObject *nam;
nam=[NSEntityDescription insertNewObjectForEntityForName:@"Class" inManagedObjectContext:managedObjectContext];

[nam setValue:nameTextField.text forKey:@"Name"];
[nam setValue:descriptionTextField.text forKey:@"Desciption"];


NSError* error;
[managedObjectContext save:&error];

[self fetchRecords]; // to show data in console
}



step 7) to display data in console we use Fetch Request


- (void)fetchRecords {

CoreData_rahul_saveDataAppDelegate* delegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext* managedObjectContext = delegate.managedObjectContext;

NSFetchRequest *request = [[NSFetchRequest alloc] init];

[request setEntity:[NSEntityDescription entityForName:@"Class" inManagedObjectContext:managedObjectContext]];

NSError *error = nil;
NSArray *events = [managedObjectContext executeFetchRequest:request error:&error];
NSAssert2(events != nil && error == nil, @"Error fetching events: %@\n%@", [error localizedDescription], [error userInfo]);
//You were leaking your request here
[request release], request = nil;
//The following line is redundant. You are leaking an array here
//NSMutableArray *namesArray = [[NSMutableArray alloc]init];
NSArray *namesArray = [events valueForKey:@"Name"];

NSLog(@"array us %@",namesArray);


}





Thanks

No comments:

FEEDJIT Live