2016-03-23 42 views
0

我试着去新值添加到使用块如下实体,只有最后一个值被插入在Coredata

[context performBlockAndWait:^{ 

        // remove all rows 
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"PendingShipmentDetails"]; 
        NSError *error; 
        NSArray * pendingShipments = [context executeFetchRequest:request error:&error]; 
        for (NSManagedObject *pendingShipment in pendingShipments) { 
         [context deleteObject: pendingShipment]; 
        } 

        // add new row(s) 

        NSManagedObject *pendingShipment = [NSEntityDescription insertNewObjectForEntityForName:@"PendingShipmentDetails" inManagedObjectContext:context]; 

        // TODO: set values here (e.g. [pendingShipment setValue:...) 
        [pendingShipment setValue:shipmentNumber forKey:@"shipmentno"]; 
        [pendingShipment setValue:proformaInvoiceNumber forKey:@"proforma_invoice_no"]; 
        [pendingShipment setValue:proformaInvoiceDate forKey:@"proforma_invoice_date"]; 
        [pendingShipment setValue:invoiceNo forKey:@"invoice_no"]; 
        [pendingShipment setValue:invoiceDate forKey:@"invoice_date"]; 
        [pendingShipment setValue:plannedShipmentDates forKey:@"planned_shipment_date"]; 
        [pendingShipment setValue:address forKey:@"point_of_contact"]; 
        [pendingShipment setValue:address forKey:@"empid"]; 
        [pendingShipment setValue:name forKey:@"products"]; 
        [pendingShipment setValue:qty forKey:@"quantity"]; 
        [pendingShipment setValue:rte forKey:@"rate"]; 
        [pendingShipment setValue:amt forKey:@"amount"]; 
        [pendingShipment setValue:img forKey:@"product_image"]; 
        [pendingShipment setValue:pendingStatus forKey:@"status"]; 

        // save MOC 
        if ([context hasChanges]) { 
         (void)[context save:&error]; 
        } 
       }]; 

首先,我想删除所有现有行 其次,我用新记录填充它。

问题是,只有最后一个值被插入。我该如何纠正它?

UPDATE:

-(void)pendingShipmentDetails 
{ 
    keyChain = [[KeyChainItemWrapper alloc] initWithIdentifier:@"LoginController" accessGroup:nil]; 
    NSString *username = [keyChain objectForKey:(__bridge id)(kSecAttrLabel)]; 

    NSString *bodyString = [NSString stringWithFormat:@"{\"method\":\"pending_shipment_details\",\"data\":{\"username\":\"%@\"}}",username]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"URL"]]; 
    NSData *postData = [bodyString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
    [request setHTTPBody:postData]; 
    [request setHTTPMethod:@"POST"]; 
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

    NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 

    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) 
    { 
     if ([data length] > 0 && connectionError == nil) 
     { 
      [self receivedPendingShipmentDetailsData:data]; 
      NSString* pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
      NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding]; 
      NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil]; 
      NSDictionary *valueDict = [jsonDic objectForKey:@"value"]; 

      NSArray *details = [valueDict objectForKey:@"details"]; 

      NSMutableArray* arrayList = [[NSMutableArray alloc] init]; 

      for (NSDictionary *response in details) { 
       NSString *invoiceNo = [response valueForKey:@"invoice_no"]; 
       NSString *shipmentNumber = [response valueForKey:@"shipment_no"]; 
       NSString *invoiceDate = [response valueForKey:@"invoice_date"]; 
       NSString *proformaInvoiceNumber = [response valueForKey:@"proforma_invoice_no"]; 
       NSString *proformaInvoiceDate = [response valueForKey:@"proforma_invoice_date"]; 
       NSString *plannedShipmentDates = [response valueForKey:@"planned_shipment_dates"]; 
       NSString *pointOfContact =[[response objectForKey:@"point_of_contact"] valueForKey:@"empid"]; 
       NSString *pendingStatus = [response valueForKey:@"status"]; 
       NSDictionary *productName = [response valueForKey:@"products"]; 
       NSDictionary *quantity = [response valueForKey:@"quantity"]; 
       NSDictionary *rate = [response valueForKey:@"rate"]; 
       NSDictionary *amount = [response valueForKey:@"amount"]; 
       NSDictionary *productImages = [response valueForKey:@"product_image"]; 
       NSDictionary *point_of_contact = [response valueForKey:@"point_of_contact"]; 

       NSString *qty; 
       NSString *rte; 
       NSString *img; 
       NSString *address; 
       NSString *name; 
       NSString *amt; 

       for (int i = 0; i < [productName count]; i++) { 
        // NSLog(@"product name %@",[productName valueForKey:[NSString stringWithFormat:@"%d",i ]]); 
        name = [productName valueForKey:[NSString stringWithFormat:@"%d",i ]]; 
       } 

       for (int i = 0; i < [quantity count]; i++) { 
        // NSLog(@"quantity %@",[quantity valueForKey:[NSString stringWithFormat:@"%d",i ]]); 
        qty = [quantity valueForKey:[NSString stringWithFormat:@"%d",i ]]; 
       } 

       for (int i = 0; i < [rate count]; i++) { 
        // NSLog(@"rate %@",[rate valueForKey:[NSString stringWithFormat:@"%d",i ]]); 
        rte = [rate valueForKey:[NSString stringWithFormat:@"%d",i ]]; 
       } 

       for (int i = 0; i < [amount count]; i++) { 
        // NSLog(@"amount %@",[amount valueForKey:[NSString stringWithFormat:@"%d",i ]]); 
        amt = [amount valueForKey:[NSString stringWithFormat:@"%d",i ]]; 
       } 


       for (int i = 0; i < [productImages count]; i++) { 
        // NSLog(@"product image %@",[productImages valueForKey:[NSString stringWithFormat:@"%d",i ]]); 
        img = [productImages valueForKey:[NSString stringWithFormat:@"%d",i ]]; 
       } 

       for (int i = 0; i < [point_of_contact count]; i++) { 
        // NSLog(@"pt of ct %@",[point_of_contact valueForKey:[NSString stringWithFormat:@"empid" ]]); 
        address = [point_of_contact valueForKey:[NSString stringWithFormat:@"empid" ]]; 
       } 


       NSManagedObjectContext *context = [self managedObjectContext]; 

       // remove all rows 
       NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"PendingShipmentDetails"]; 
       NSError *error; 
       NSArray * pendingShipments = [context executeFetchRequest:request error:&error]; 


       [context performBlockAndWait:^{ 


        // add new row(s) 
        NSLog(@"else block"); 
        NSManagedObject *pendingShipment = [NSEntityDescription insertNewObjectForEntityForName:@"PendingShipmentDetails" inManagedObjectContext:context]; 
        NSError *error; 

        for (NSManagedObject *pendingShipment in pendingShipments) { 
         [context deleteObject: pendingShipment]; 

        } 
        // TODO: set values here (e.g. [pendingShipment setValue:...) 
        [pendingShipment setValue:shipmentNumber forKey:@"shipmentno"]; 
        [pendingShipment setValue:proformaInvoiceNumber forKey:@"proforma_invoice_no"]; 
        [pendingShipment setValue:proformaInvoiceDate forKey:@"proforma_invoice_date"]; 
        [pendingShipment setValue:invoiceNo forKey:@"invoice_no"]; 
        [pendingShipment setValue:invoiceDate forKey:@"invoice_date"]; 
        [pendingShipment setValue:plannedShipmentDates forKey:@"planned_shipment_date"]; 
        [pendingShipment setValue:address forKey:@"point_of_contact"]; 
        [pendingShipment setValue:address forKey:@"empid"]; 
        [pendingShipment setValue:name forKey:@"products"]; 
        [pendingShipment setValue:qty forKey:@"quantity"]; 
        [pendingShipment setValue:rte forKey:@"rate"]; 
        [pendingShipment setValue:amt forKey:@"amount"]; 
        [pendingShipment setValue:img forKey:@"product_image"]; 
        [pendingShipment setValue:pendingStatus forKey:@"status"]; 

        // save MOC 
        if ([context hasChanges]) { 
         (void)[context save:&error]; 
        } 
       }]; 

      } 
     } 

     else if ([data length] == 0 && connectionError == nil) 
     { 
      [self emptyReply]; 
     } 
     else if (connectionError != nil && connectionError.code == NSURLErrorTimedOut) 
     { 
      [self timedOut]; 
     } 
     else if (connectionError != nil) 
     { 
      [self downloadError:connectionError]; 
     } 
    }]; 

} 
+1

在'for-in'循环中,每次循环时删除** all ** PendingShipmentDetails'Entities',然后添加新值。所以在最后一个循环中,您最终只会得到一个不会被删除的实体。 – Khundragpan

+0

你能告诉我怎样才能解决这个问题 –

+0

你有任何独特的属性,即'NSDate'?你以什么标准删除你的对象?您需要简要介绍应删除或更新或插入哪个对象。或者在每个提取上删除所有早期的对象。 – Khundragpan

回答

1

如果您打算在每次新获取数据时删除之前获取的所有对象。然后,您应该首先通过为该实体调用NSFetchRequest来删除所有持久化对象,然后使用for-in循环添加值,就像您在做的那样。您可以使用NSBatchDeleteRequest

//某些方法或IBAction刷新数据 //首先删除所有旧的。

-(void) deleteStoredData 
{ 

    NSManagedObjectContext *context = [self managedObjectContext]; 
[context performBlock:^{ 
       // remove all rows 
       NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"PendingShipmentDetails"]; 
       NSError *error; 
       NSArray * pendingShipments = [context executeFetchRequest:request error:&error]; 
for (NSManagedObject *pendingShipment in pendingShipments) { 
    [context deleteObject: pendingShipment]; 
    } 
}]; 

[self pendingShipmentDetails]; 
} 

现在您的pendingShipmentDetails将是相同的,虽然删除的对象。

-(void) pendingShipmentDetails{ 
// do saving using loop 
} 
+0

谢谢你它的魅力 –

1

你所示的代码不通过新的价值循环 - 所以只有一个被插入的值。

如果您循环显示新数据时显示的代码被多次调用,那么它首先会删除所有内容 - 无论哪种方式,最终只会有一个条目。

如果您正在实施第二种方法,则需要在删除新数据之前拆分删除块,然后执行一次。

+0

请您参考我的代码来提倡吗?谢谢 –

+0

在上面的代码中 - 每次调用performBlockAndWait时,都会执行'remove all rows'部分,但'add new row(s)'部分只会调用一次。你可以添加你调用这个块的代码吗? – Russell

+0

该块已在方法中。因此如果该方法被调用,则该块将自动执行。我将整个方法发布 –