如何在Objective C的核心数据中保存数组的剩余数据

Posted

技术标签:

【中文标题】如何在Objective C的核心数据中保存数组的剩余数据【英文标题】:How to save remaning data of array in core data in Objective C 【发布时间】:2017-02-14 11:33:42 【问题描述】:

我是 ios 新手,我在将数组的剩余数据保存在核心数据中时遇到问题。 如图所示

我从表格视图中选择了一个按钮,它将价值保存在核心数据中

为此我的代码是这样的

 NSString *FailString=@"";
    NSString *WarningString=@"";

    NSManagedObjectContext *context = [self managedObjectContext];
    NSError *error;

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"AuditPost" inManagedObjectContext:context]];

    //  NSError *error = nil;
    NSArray *results = [context executeFetchRequest:request error:&error];
    NSLog(@"Result =%@",results);

    int imageSize   = imgData.length;
    NSLog(@"size of image in KB: %d ", imageSize/1024);
    int OCS=imageSize/1024;

    NSLog(@"OCS Image Size =%d",OCS);

    if(OCS<2)
    
        AuditImageString=@"";
    

    ComplareArray=[devices valueForKey:@"checkpointid"];

    BOOL contains = [ComplareArray containsObject:String2];

    if(contains == NO)
    
        if (self.device) 
            // Update existing device
            [device setValue:Audit forKey:@"auditnameId"];
            [device setValue:String forKey:@"checklistid"];
            [device setValue:String2 forKey:@"checkpointid"];
            [device setValue:FailString forKey:@"failreason"];
            [device setValue:WarningString forKey:@"warningreason"];
            [device setValue:AuditStartDate forKey:@"starttimedate"];
            [device setValue:userid forKey:@"userid"];
            [device setValue:AuditImageString forKey:@"auditimage"];

            NSError *error = nil;
            // Save the object to persistent store
            if (![context save:&error]) 
                NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
            

         else 
            // Create a new device
            NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"AuditPost" inManagedObjectContext:context];
            [newDevice setValue:Audit forKey:@"auditnameId"];
            [newDevice setValue:String forKey:@"checklistid"];
            [newDevice setValue:String2 forKey:@"checkpointid"];
            [newDevice setValue:FailString forKey:@"failreason"];
            [newDevice setValue:WarningString forKey:@"warningreason"];
            [newDevice setValue:AuditStartDate forKey:@"starttimedate"];
            [newDevice setValue:userid forKey:@"userid"];
            [newDevice setValue:AuditImageString forKey:@"auditimage"];

            NSError *error = nil;
            // Save the object to persistent store
            if (![context save:&error]) 
                NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
            
        
    
    else
    
        NSError *error = nil;
        // Save the object to persistent store
        if (![context save:&error]) 
            NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
        

        NSManagedObjectContext *context = [self managedObjectContext];

        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        [request setEntity:[NSEntityDescription entityForName:@"AuditPost" inManagedObjectContext:context]];

        NSArray *results = [context executeFetchRequest:request error:&error];
        NSManagedObject* favoritsGrabbed = [results objectAtIndex:CurrentIndexPath];
        [favoritsGrabbed setValue:String forKey:@"checklistid"];
        // Save the object to persistent store
        if (![context save:&error]) 
            NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
        
    

    //example reload table
    dispatch_async(dispatch_get_main_queue(), ^
        [Audittable reloadData];
    );  

为了将整个数组保存在核心数据中,我使用这样的代码

if (self.device)
            
                // Update existing device
                [device setValue:Audit forKey:@"auditnameId"];
                [device setValue:[NSString stringWithFormat:@"%@",Passarray[i]] forKey:@"checklistid"];
                [device setValue:[NSString stringWithFormat:@"%@",CheckpointNameIDArray[i]] forKey:@"checkpointid"];
                [device setValue:FailString forKey:@"failreason"];
                [device setValue:WarningString forKey:@"warningreason"];
                [device setValue:AuditStartDate forKey:@"starttimedate"];
                [device setValue:userid forKey:@"userid"];
                [device setValue:[NSString stringWithFormat:@"%@",AuditImageString] forKey:@"auditimage"];
                NSError *error = nil;
                // Save the object to persistent store
                if (![context save:&error]) 
                    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
                
            
            else
            
                // Create a new device
                NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"AuditPost" inManagedObjectContext:context];
                [newDevice setValue:Audit forKey:@"auditnameId"];
                [newDevice setValue:[NSString stringWithFormat:@"%@",Passarray[i]] forKey:@"checklistid"];
                [newDevice setValue:[NSString stringWithFormat:@"%@",CheckpointNameIDArray[i]] forKey:@"checkpointid"];
                [newDevice setValue:FailString forKey:@"failreason"];
                [newDevice setValue:WarningString forKey:@"warningreason"];
                [newDevice setValue:AuditStartDate forKey:@"starttimedate"];
                [newDevice setValue:userid forKey:@"userid"];
                [newDevice setValue:[NSString stringWithFormat:@"%@",AuditImageString] forKey:@"auditimage"];

                NSError *error = nil;
                // Save the object to persistent store
                if (![context save:&error]) 
                    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
                
             
            
            for (int i=0; i<PassarrIndexPaths.count; i++)
            
                AuditNextTableViewCell *cell = [Audittable cellForRowAtIndexPath:[PassarrIndexPaths objectAtIndex:i]];
                DataModel *model = [arrData objectAtIndex:i];
                model.strSelected = @"P";
                [cell.passbtn setBackgroundColor:[UIColor greenColor]];
                [cell.failbtn setBackgroundColor:[UIColor lightGrayColor]];
                [cell.wipbtn setBackgroundColor:[UIColor lightGrayColor]];
                [cell.nabtn setBackgroundColor:[UIColor lightGrayColor]];
            
//            Passbtn.backgroundColor=[UIColor greenColor];
//            NAbtn.backgroundColor=[UIColor lightGrayColor];
            [Audittable reloadData];

如图所示 如果我点击 Mark Pending As PASS,它会将剩余的数组元素保存在未选择的核心数据中。对于选择,我使用这样的代码

NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
            NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"AuditPost"];
            self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

            for (int i=0; i<PassarrIndexPaths.count; i++)
            
                AuditNextTableViewCell *cell = [Audittable cellForRowAtIndexPath:[PassarrIndexPaths objectAtIndex:i]];
                DataModel *model = [arrData objectAtIndex:i];

                if([model.strSelected isEqualToString:@"P"])
                

                
                else if ([model.strSelected isEqualToString:@"W"])
                

                
                else if ([model.strSelected isEqualToString:@"F"])
                

                
                else if ([model.strSelected isEqualToString:@"NA"])
                

                
                else if ([model.strSelected isEqualToString:@"NAA"])
                

                
                else
                
                    model.strSelected = @"PA";
                    [cell.passbtn setBackgroundColor:[UIColor greenColor]];
                    [cell.failbtn setBackgroundColor:[UIColor lightGrayColor]];
                    [cell.wipbtn setBackgroundColor:[UIColor lightGrayColor]];
                    [cell.nabtn setBackgroundColor:[UIColor lightGrayColor]];
                

我面临的问题是,如果我在核心数据中保存一些数据。如何在核心数据中保存数组的剩余数据。有人这样做过吗。谢谢 Adnavce!

【问题讨论】:

剩余数据是什么意思? 创建管理对象模型并保存管理对象上下文。 @Mukesh 如图所示,我已将数组中的一个字符串保存在核心数据中。单击 Select all As Pass 我需要保存数组的剩余数据意味着跳过第一个索引并保存另一个值核心数据中的数组。有可能吗? @Jitendra 怎么做? @Muju 参考此链接appcoda.com/core-data-tutorial-update-delete 【参考方案1】:

如果我是正确的,你想保存数据库中尚不存在的数据对象做简单,

-(void)save_UpdateData:(NSArray *)yourArray 

    NSManagedObjectContext *_context = [self getManagedObjectContext];

     for(int i = 0; i < [yourArray count]; i++) 
        NSDictionary *details = [yourArray objectAtIndex:i];
        NSArray *_arrayMappingObjects = [self getSavedDataFromDB];
        //Lets check mapping object exist in current record or not.
        //If not exist then create new one and add the same
        //If already exist, No need to add.
        NSPredicate *_predicate = [NSPredicate predicateWithFormat:@"yourKey_predicate_id=%@",[NSNumber numberWithInt:[[details objectForKey:@"yourKey_predicate_id"] intValue]]];
        _arrayMappingObjects = [_arrayMappingObjects filteredArrayUsingPredicate:_predicate];
        if([_arrayMappingObjects count] > 0) 

          //Object already exist, No need to add the same object.

         else 
            // Lets create an object add newly created instance
            ModelClass *modelObject = [NSEntityDescription insertNewObjectForEntityForName:@"ModelClass" inManagedObjectContext:_context];
            [modelObject setEntityName1:[details objectForKey:@"key1"]];//If your property is NSString
            [modelObject setEntityName2:[NSNumber numberWithInt:[[details objectForKey:@"key2"] intValue]]];//If your property is NSNumber
            [modelObject setEntityName3:[NSNumber numberWithInt:[[details objectForKey:@"key3"] intValue]]];

            [self saveContext];
        
    

//获取保存的数据

-(NSMutableArray *)getSavedDataFromDB 

    NSMutableArray *_record = [[NSMutableArray alloc] initWithCapacity:0];

    NSManagedObjectContext *_context =[self getManagedObjectContext];
    NSFetchRequest *_fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *_entityDesc =[NSEntityDescription entityForName:@"ModelClass" inManagedObjectContext:_context];
    [_fetchRequest setEntity:_entityDesc];

    NSError *_error;
    NSArray *_fetchedOjects = [_context executeFetchRequest:_fetchRequest error:&_error];

    for(int i=0;i<[_fetchedOjects count];i++) 
        ModelClass *modelObject = [_fetchedOjects objectAtIndex:i];
        [_record addObject:modelObject];
    
    return _record;

【讨论】:

将此视为通用解决方案。你可以根据你的依赖改变你的代码和逻辑。

以上是关于如何在Objective C的核心数据中保存数组的剩余数据的主要内容,如果未能解决你的问题,请参考以下文章

如何从 Objective C、iOS 中的 NSUserDefaults 获取准确数据?

在 Objective-C 中按评论数量对核心数据中的 FetchedObjects 数组进行排序

iPhone Objective C - 保存数据

iOS/Objective-C:在后台线程中保存到核心数据

ios/objective-c:保存核心数据时出错

如何保存变量并从两个不同的类中使用它Objective C