2012-02-28 132 views
0

我無法將保存的數據從CoreData導出到CSV文件。我的最終目標是將信息保存爲CSV並將其附加到電子郵件中。這裏是我的代碼,用於導出數據:NSArray可能無法響應(導出爲CSV代碼錯誤)

- (IBAction)exportData 
{ 
mieleWasherAppDelegate *exportObjects = [[mieleWasherAppDelegate alloc] init]; 
[exportObjects managedObjectContext]; 
NSFetchRequest * allContacts = [[NSFetchRequest alloc] init]; 
[allContacts setEntity:[NSEntityDescription entityForName:@"Contacts"  inManagedObjectContext: [exportObjects managedObjectContext]]]; 
// [allContacts setIncludesPropertyValues:YES]; //only fetch the managedObjectID 

NSError * error = nil; 
NSArray * entries = [[exportObjects managedObjectContext] executeFetchRequest:allContacts error:&error]; 
[allContacts release]; 
//error handling goes here 
NSMutableArray *array = [[NSMutableArray alloc] init]; 

for (Contacts * entry in entries) 
{ 
    NSLog(@"Salutation: %@", entry.Salutation); 
    NSLog(@"First Name: %@", entry.FirstName); 
    NSLog(@"Last Name: %@", entry.LastName); 
    NSLog(@"Company Name: %@", entry.CompanyName); 
    NSLog(@"Email Address: %@", entry.EmailAddress); 
    NSLog(@"Phone Number: %@", entry.PhoneNumber); 
    [array addObject:entry]; 
} 
NSError *saveError = nil; 
[[exportObjects managedObjectContext] save:&saveError]; 
//more error handling here 

// Export to CSV code 
NSString *separator = @", "; 
NSString *csv = @""; 
for (NSArray *entry in entries) 
{ 
    csv = [NSString stringWithFormat:@"%@%@%@%@%@\n", csv, [entry Salutation], 
      separator, [entry FirstName], 
      separator, [entry LastName], 
      separator, [entry CompanyName], 
      separator, [entry EmailAddress], 
      separator, [entry PhoneNumber]]; 
} 
//If you want to store in a file the CVS 
//[csv writeToFile:pathToFile atomically:YES]; 
//If you want to store in a file the CVS 
//[cvs writeToFile:pathToFile atomically:YES]; 
} 

很抱歉,如果格式是有點亂,但它返回下面的警告(重複):

NSArray的可能不是「-Salutation」

迴應

等,直到它遍歷所有領域。我似乎無法弄清楚爲什麼它不會合作。有什麼建議?

回答

2

在代碼的第二for循環複製&上面粘貼,你聲明entry作爲NSArray對象,而不是Contacts對象。

NSArray更改爲Contacts並且警告將消失。

+0

非常好,這工作。非常感謝。作爲附錄,是否有代碼在打印輸出中檢查空條目?例如,如果我留下一個空白條目,它不應該保存它,但它似乎是當我去打印結果。有什麼我可以做的嗎? – 2012-02-28 15:34:38