如何在核心数据中添加 NSDictionary 任何文档或示例代码都会有所帮助。提前致谢。
问问题
91 次
1 回答
0
在新项目窗口中,选择任何模板选项。在窗口的选项部分中,确保选中使用核心数据进行存储旁边的复选框,单击选择
在里面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
在您的视图控制器:
// 保存数据
- (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];
}
// 检索数据
- (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];
}
它可以正常工作
于 2012-09-02T09:35:39.333 回答