如何从此阵列创建自定义字符串?

时间:2011-12-22 23:50:19

标签: iphone objective-c pdf core-data nsarray

您好我使用以下方法从核心数据创建了一个数组:

NSArray* invoiceItem =[fetchedResultsController fetchedObjects];

根据日志返回以下内容:

"<Invoice: 0x8545900> (entity: Invoice; id: 0x8542dd0 <x-coredata://AF2BBB5C-4135-45EB-A421-5036AE02D2A0/Invoice/p19> ; 
data: {\n    GSTAmount = \"0.75\";\n    amountPaid = nil;\n    cardID = 0;\n    
customer = \"\";\n    date = \"23/12/2011\";\n    incTaxPrice = \"8.25\";\n    
incTaxTotal = \"8.25\";\n    invoiceNumber = a20;\n    itemCode = 1035;\n    
paymentMethod = nil;\n    price = \"7.50\";\n    quantity = 1;\n    saleStatus = I;\n
taxCode = GST;\n    timeStamp = \"2011-12-22 22:10:25 +0000\";\n    total = \"7.5\";\n})",

 "<Invoice: 0x8545c00> (entity: Invoice; id: 0x8543390 <x-coredata://AF2BBB5C-4135-45EB-A421-5036AE02D2A0/Invoice/p20> ; 
data: {\n    GSTAmount = \"0.55\";\n    amountPaid = nil;\n    cardID = 0;\n    
customer = \"\";\n    date = \"23/12/2011\";\n    incTaxPrice = \"6.05\";\n    
incTaxTotal = \"12.1\";\n    invoiceNumber = a20;\n    itemCode = 1040;\n    
paymentMethod = nil;\n    price = \"5.50\";\n    quantity = 2;\n    saleStatus = I;\n
taxCode = GST;\n    timeStamp = \"2011-12-22 22:11:14 +0000\";\n    total = 11;\n})"
)

我的总体目标是简单地创建一个itemCode属性的字符串格式化,以便它可以是pdf中的一列,因为我不知道除了创建tableview的图像和插入之外的任何其他方式制作表在PDF中。我想避免这样做。

所以我试图从上面的数组中获取一个字符串,格式如下

"1035\n1040"

我不知道如何从数组中获取项代码属性。请注意,项目代码的长度会有所不同,并不总是只是数字。

任何帮助将不胜感激!如果有人有任何其他提示或更好的方法来实现我想要做的事情,我会全神贯注:)

修改

纯粹是为了解决方案的广泛性。在我离开电脑几分钟后,我碰巧想出了一个解决方案。我不会使用我的解决方案,因为另一个似乎更有效/至关重要。但是我想我会为其他人提供另一种方法。

NSMutableArray *itemCodes =[invoiceItem mutableArrayValueForKey:@"itemCode"];
NSString *holdingString =[NSString stringWithFormat:@"%@",itemCodes];
NSString *itemColumn = [holdingString stringByReplacingOccurrencesOfString:@"," withString:@"\n"];

2 个答案:

答案 0 :(得分:0)

您在日志中看到的是数组的字符串表示形式。您可以通过调用[发票说明]来获取此字符串。但是,除了日志输出之外,你真的不想使用它。

您真正想做的是逐个浏览数组对象并提取相关信息。

//Create your string
NSMutableString *string = [[NSMutableString alloc] initWithCapacity:0];

//Enumerate through the array
//Not sure how your entities are set up, but you'll want to generate your Invoice subclass and include the header
for (Invoice *invoice in invoiceItem) //by the way, I would suggest calling the array invoiceItems as it indicates more than one invoice
{
   //This will add the item code and a new line character to your string
   [string appendStringWithFormat:@"%@\n", invoice.itemCode];
}
//Now that the loop is finished you have a string of all of the items codes on their own line. There is an extra newline at the end that you may not need.

答案 1 :(得分:0)

首先获取所需值的数组。然后用字符串连接这些值。在你的情况下是一个换行符。

NSArray *itemCodes = [invoiceItem valueForKey:@"itemCode"];
NSString *itemCodeString = [itemCodes componentsJoinedByString:@"\n"];

您可以迭代Invoice托管对象的实体(NSEntityDescription)属性的属性,并创建由每个属性的名称键入的格式正确的字符串的字典。

如果我可能会建议一些可能使您的代码更具可读性的微小更改。而不是

NSArray *invoiceItem;  

您可以考虑将变量重命名为invoiceItems或result,以帮助将变量标识为“容器”而不是“实例”。