How to add a NSDictionary in core data any documentation or sample codes would be help full. thanks in advance.
Asked
Active
Viewed 97 times
1 Answers
0
In the new project window, select any template 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
in the AppDelegate.h
@class coreDataViewController;
@interface coreDataAppDelegate : NSObject <UIApplicationDelegate> {
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
coreDataViewController *viewController;
UIWindow *window;
}
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet coreDataViewController *viewController;
- (NSString *)applicationDocumentsDirectory;
@end
at your viewController:
// To save Data
- (void) saveData
{
coreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newContact;
newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:context];
[newContact setValue:@"anyData" forKey:@"anyKeyInDataBase"];
[newContact setValue:@"anyData" forKey:@"anyKeyInDataBase"];
[newContact setValue:@"anyData" forKey:@"anyKeyInDataBase"];
NSError *error;
[context save:&error];
}
// To Retrive Data
- (void) 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:@"(yourPrimaryKey = %@)", @"theKeyYouSearchFor"];
[request setPredicate:pred];
NSManagedObject *matches = nil;
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if ([objects count] == 0) {
NSLog( @"No matches");
} else {
matches = [objects objectAtIndex:0];
NSLog( @"%@",[matches valueForKey:@"anyKey"]);
NSLog( @"%@",[matches valueForKey:@"anyKey"]);
NSLog( @"%@",[matches valueForKey:@"anyKey"]);
}
[request release];
}
it shold work fine

Mutawe
- 6,464
- 3
- 47
- 90