2012-05-27 39 views
0

在Objective-C中,使用核心數據,我正在獲取實體並將它們作爲NSArrays返回。我意識到我經常抓取,我可以利用實體​​的返回值,例如:客戶實體有很多發票,發票有很多ItemSold。下面是一些代碼我使用:爲什麼我的NSArray變成了NSSet?

NSError *error = nil; 
// fetch all customers 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Customer" 
              inManagedObjectContext:managedObjectContext]; 
[fetchRequest setEntity:entity]; 
self.fetchedCustomers = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; 
if (fetchedCustomers == nil) { 
    NSLog(@"ERROR"); 
} 
[fetchRequest release]; 
// end of customer fetch 

這是簡單讀取請求,並fetchedCustomers被設置爲一個NSArray財產。然後,我使用它的功能:

self.fetchedInvoices = [[customerToView valueForKey:@"invoices"] allObjects];

這工作,我能夠正確顯示發票號和日期​​到一個表。不過,我接下來要使用:

self.fetchedObjects = [[fetchedInvoices valueForKey:@"itemsSold"] allObjects]; 

後來,當我嘗試添加總計我做了以下內容:

double price = [[[fetchedObjects objectAtIndex:i] valueForKey:@"Price"] doubleValue]; 

而且我得到以下錯誤:

-[__NSCFSet doubleValue]: unrecognized selector sent to instance 0x10228f730 

爲什麼有沒有涉及NSSet?當我使用謂詞獲取發票和項目時,我沒有任何問題,但它看起來效率很低。我寧願弄清楚這裏出了什麼問題。任何幫助將不勝感激,謝謝。

額外的信息:感興趣

地區:

@interface Invoice : NSManagedObject { 
@private 
} 
@property (nonatomic, retain) NSSet *itemsSold; 
@end 

@interface Invoice (CoreDataGeneratedAccessors) 

- (void)addItemsSoldObject:(ItemSold *)value; 
- (void)removeItemsSoldObject:(ItemSold *)value; 
- (void)addItemsSold:(NSSet *)values; 
- (void)removeItemsSold:(NSSet *)values; 

@end 
+1

是什麼類型的房地產價格? – lnafziger

+0

這是一個NSNumber。 – Rail24

+0

你確定嗎?嘗試'NSLog([[[fetchedObjects objectAtIndex:i] valueForKey:@「Price」] class];'在你的行加上'doubleValue'之前 – lnafziger

回答

0

我意識到我的錯誤。我將提取的顧客分類到特定的「customerToView」中。我沒有對我的fetchedInvoices做同樣的事情。所以我的解決方案如下:

NSManagedObject *invoiceToView = [fetchedInvoices objectAtIndex:(int)[invoicesTable selectedRow]]; 

並在fetchedInvoices的地方使用invoiceToView。

我的部分愚蠢的錯誤!

+0

是的,自我。fetchedInvoices在你的問題是一個NSSet的數組:) –

0

嘗試這樣做:

NSString *className = NSStringFromClass([[[fetchedObjects objectAtIndex:i] valueForKey:@"Price"] class]); 
NSLog(@"class name: %@", className); 

,以確保你得到了什麼類型。

+0

所以我得到:'' class name:__NSCFSet 2012-05-27 13:10:26.379 InventoryProgram [57463:707] {( 399,)}',但我的核心數據模型將其建模爲NSNumber,並在我的頭文件I有: '@property(nonatomic,retain)NSNumber * Price;' – Rail24

+0

嘗試從設備/模擬器中刪除應用程序,然後再清理並重新運行只是爲了確保您的模型與持久存儲相匹配我知道它會拋出不同的異常,但只要試一試。 – Adam

0

[fetchedObjects objectAtIndex:i]在這裏似乎是一個NSSet。 [[fetchedObjects objectAtIndex:i] valueForKey:@「Price」]將獲得關鍵字爲「Price」的所有對象,並且它是一個NSSet。祝你好運!

相關問題