2011-12-22 59 views
0

您好我已創建使用從核心數據的數組:如何從這個數組中創建一個自定義字符串?

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"]; 

回答

0

首先獲取所需值的數組。然後用一個字符串連接這些值。在你的情況下換行符。

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

你可以遍歷實體您的發票管理對象(NSEntityDescription)財產的屬性並創建每個屬性的名稱鍵正確格式化字符串的字典。

如果我可能會提出一個小的更改,可以使您的代碼更具可讀性。取而代之的

NSArray *invoiceItem; 

你可能會考慮重新命名變量invoiceItems或結果,以幫助識別變量,而不是一個「實例」的「容器」。

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. 
相關問題