Core Data in IPhone


In this tutorial we will learn about the Core Data in IPhone.Xcode will create the new project and display the main project window. In addition to the usual files that are present when creating a new project, this time an additional file named coreData.xcdatamodel is also created. This is the file where the entity descriptions for our data model are going to be stored.The entity description defines the model for our data, much in the way a schema defines the model of a database table. To create the entity for the Core Data application, double click on the coreData.xcdatamodel file to load the entity editor.Here are some step for that..

.

 

1. Open the xcode & choose "File->New Project".

2. To create the example application project, launch Xcode and select the option to create a new project. In the new project window, select the Window-based Application option. In the Options section of the window make sure that the check box next to Use Core Data for storage is selected, click the Choose... button and name the project coreData.

3.Name your project as "CoreData" and save the project.

4.In order to add Core Data support to our application we had to choose the Window-based Application project template option when we started Xcode. As such, we now need to create our own view controller.

5.Now that we have added the view controller class to the application we need to modify our app delegate to make this the root view controller. In the main Xcode project window, select the coreDataAppDelegate.h file and modify it to add references to our view controller:

 

 

 

import <UIKit/UIKit.h>

#import <CoreData/CoreData.h>

#import "DetailViewController.h"

 

@class DetailViewController;

 

 

@interface CoreDataAppDelegate : NSObject <UIApplicationDelegate> {

    

    //DetailViewController *viewController;

 

UIWindow *window;

 

 

    

@private

 

    NSManagedObjectContext *managedObjectContext_;

 

 

 

    NSManagedObjectModel *managedObjectModel_;

 

 

 

    NSPersistentStoreCoordinator *persistentStoreCoordinator_;

 

 

}

 

 

@property (nonatomic, retain) IBOutlet UIWindow *window;

 

 

 

@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;

@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;

@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;

//@property(nonatomic,retain) DetailViewController *viewController;

- (NSString *)applicationDocumentsDirectory;

 

@end

6. Now select "CoreDataAppDelegate.m" file from menu for implementation.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    // Override point for customization after application launch.

DetailViewController *viewController=[[DetailViewController alloc]init];

[window addSubview:viewController.view];

    [window makeKeyAndVisible];

return YES;

}

 

- (void)applicationWillTerminate:(UIApplication *)application {

    

    NSError *error = nil;

    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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

             */

            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

            abort();

        } 

    }

}

 

 

- (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:@"CoreData" 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 = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CoreData.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_;

}

 

- (void)dealloc {

    

    [managedObjectContext_ release];

    [managedObjectModel_ release];

    [persistentStoreCoordinator_ release];

    

    [window release];

    [super dealloc];

}

 

 

@end

 

7. Now select "DetailViewController.h" file from menu for implementation.

 

#import <UIKit/UIKit.h>

 

 

@interface DetailViewController : UIViewController {

UITextField *name;

UITextField *address;

UITextField *phone;

UILabel         *status;

 

}

@property(nonatomic,retain)IBOutlet UITextField *name;

@property(nonatomic,retain)IBOutlet UITextField *address;

@property(nonatomic,retain)IBOutlet UITextField *phone;

@property(nonatomic,retain)IBOutlet UILabel         *status;

 

- (IBAction) saveData;

- (IBAction) findContact;

 

 

@end

 

7. Now select "DetailViewController.m" file from menu for implementation.

 

#import "DetailViewController.h"

#import "CoreDataAppDelegate.h"

 

@implementation DetailViewController

@synthesize name,address,phone,status;

- (IBAction) saveData{

 

CoreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSManagedObject *newContact;

newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:context];

[newContact setValue:name.text forKey:@"name"];

[newContact setValue:address.text forKey:@"Address"];

[newContact setValue:phone.text forKey:@"phone"];

name.text = @"";

address.text = @"";

phone.text = @"";

NSError *error;

[context save:&error];

//status.textLabel.text = @”Contact saved”;

status.text=@"contact saved";

 

}

 

 

 

- (IBAction) findContact{

 

CoreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Contacts" inManagedObjectContext:context];

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

[request setEntity:entityDesc];

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

[request setPredicate:pred];

NSManagedObject *matches = nil;

NSError *error;

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

if ([objects count] == 0) {

status.text = @"No matches";

else {

matches = [objects objectAtIndex:0];

address.text = [matches valueForKey:@"address"];

phone.text = [matches valueForKey:@"phone"];

status.text = [NSString stringWithFormat:@"%d matches found", [objects count]];

}

[request release];

 

 

}

- (void)viewDidUnload {

    [super viewDidUnload];

self.name = nil;

self.address = nil;

self.phone = nil;

self.status = nil;

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

[name resignFirstResponder];

[address resignFirstResponder];

[phone resignFirstResponder];

 

}

 

- (void)dealloc {

    

[name release];

[address release];

[phone release];

[status release];

[super dealloc];

}

 

 

@end


 

6. Now double click on "DetailViewController.xib" from Resource folder for open it.


7. On the view window drag the label,button and two textfield from library . Then link the label and textfields to the File's Owner. And link the button to IBActon method.


8. Then Quit and Save the Interface Builder.


9. Now you are ready for  click on "Build & Go" button. 


Now you can see the output in iphone simulator .


 



(2) Responses to this post

sam Jan 28 2011 at 06:14:57

http://stackoverflow.com/questions/2121796/how-to-retrieve-friends-list-using-facebook-connect-with-iphone-app

Dash May 06 2011 at 03:15:07

I'm impressed! You've managed the almost ipmossible.


Leave your comment here






User Login




New User Forgot password

Newsletter Subscribe

Advertisement

 
 
 
quick contact