Fetching all data from an Entity and printing only displays the last record

前端 未结 2 1769
时光说笑
时光说笑 2021-01-29 14:57

I\'m trying to fetch all of the data from a particular Core Data Entity and place each record into a string. However the following code only prints the LAST record that it acce

2条回答
  •  孤独总比滥情好
    2021-01-29 15:33

    To fix your initial problem you need to use an NSMutableString. There is no need for formattedData variable.

    ...
    NSMutableString * printedData = [NSMutableString string];
    ...
    
    for(NSManagedObject * info in fetchedObjects)
    {
        ...
        [printedData appendFormat:@"|%@|%@|%@|%@|%@|%@|%@|%@|%@|\n",clientName,clientAccount,productCode,productQuantity,productPrice,orderID,transactionID,orderTotal,salesRepID];
    }
    ...
    

    Your next issue is how inefficient this code is. You are looping over the same collection twice, once to log, once to create a formatted string. You can combine this into one loop. Also all of the variables are defined outside of the scope of the for loop that they are used in, you could simply just declare each one on a line like this.

    for(NSManagedObject * info in fetchedObjects)
    {
        NSString *clientName = [info valueForKey:@"clientName"];
        NSString *clientAccount =  [info valueForKey:@"clientAccountNumber"];
        ...
        //Log them all
        NSLog(@"%@",clientName);
        NSLog(@"%@",clientAccount);
        ...
    }
    

提交回复
热议问题