在iOS中插入和检索(核心数据)

时间:2015-01-15 04:35:08

标签: ios core-data ios7 nsmanagedobjectcontext

我正在尝试将数据插入到CoreData iOS中。为此,我在名为 DatabaseOperation

的单独文件中创建了以下函数
+(NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
    context = [delegate managedObjectContext];
}
return context;
}

+(void)storeCodeSearchData:(NSMutableArray*)data{

for (NSDictionary* rowData in data) {

    NSManagedObjectContext *context = [self managedObjectContext];
    // Create a new managed object
    NSManagedObject *codeSearchDataObject = [NSEntityDescription insertNewObjectForEntityForName:CODE_SEARCH_ENTITY inManagedObjectContext:context];
    [codeSearchDataObject setValue:[rowData objectForKey:SKU_CODE] forKey:CODE_NID];
    [codeSearchDataObject setValue:[rowData objectForKey:NID] forKey:CODE_ID];
    [codeSearchDataObject setValue:[rowData objectForKey:NEEDLE_DESCRIPTION] forKey:CODE_NEEDLE_DESC];
    [codeSearchDataObject setValue:[rowData objectForKey:NEEDLE_DIMENSION] forKey:CODE_NEEDLE_DIMENSION];
    [codeSearchDataObject setValue:[rowData objectForKey:SUTURE_TYPE] forKey:CODE_SUTURE];
    [codeSearchDataObject setValue:[rowData objectForKey:SIZE] forKey:CODE_SIZE];
    [codeSearchDataObject setValue:[rowData objectForKey:FOILS_PER_BOXEX] forKey:CODE_FOILS];
    [codeSearchDataObject setValue:[rowData objectForKey:HOSPITAL_PRICE] forKey:CODE_RETAILS_HOSPITAL];
    [codeSearchDataObject setValue:[rowData objectForKey:MAXIMUM_RETAILS] forKey:CODE_MAX_RETAIL];
    NSError *error = nil;
    BOOL *saveResult = [context save:&error];
    NSLog(saveResult ? @"Yes" : @"No");
    // Save the object to persistent store
    if (!saveResult) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
  }  
}

NSLog正在打印"Yes"。 我从其他implementation文件调用此函数,如下所示:

[DatabaseOperation storeCodeSearchData:datas];

我的datas是一个NSMutableArray,正在存储NSDictionary,如下所示:

NSMutableDictionary *resultantDataObject = [[NSMutableDictionary alloc]init];
 resultantDataObject[KEY1] = @"nc";
 resultantDataObject[KEY2] = @"c";
[datas addObject:resultantDataObject];

但是当我尝试获取数据null时。下面是获取我正在使用的数据的方法:

 NSManagedObjectContext *managedObjectContext = [DatabaseOperation managedObjectContext];

   NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:CODE_SEARCH_ENTITY];
            NSDictionary *datasAA = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
            NSLog(@"Data Retrieve: %@",datasAA);

感谢您的帮助

0 个答案:

没有答案