为什么我的NSArray变成NSSet?

时间:2012-05-27 16:44:15

标签: objective-c core-data nsarray nsset

在Objective-C中,使用核心数据,我获取实体并将它们作为NSArrays返回。我意识到我经常抓取,我可以利用实体​​的返回值,例如:客户实体有很多发票,发票有很多ItemSolds。这是我正在使用的一些代码:

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

3 个答案:

答案 0 :(得分:0)

尝试这样做:

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

确保你得到的是什么类型。

答案 1 :(得分:0)

[fetchedObjects objectAtIndex:i]在这里似乎是一个NSSet。 [[fetchedObjects objectAtIndex:i] valueForKey:@“Price”]将获得具有键“Price”的所有对象,并且它是NSSet。祝你好运!

答案 2 :(得分:0)

我意识到自己的错误。我正在将fetchedCustomers分类为特定的“customerToView”。我的fetchedInvoices没有做同样的事情。所以我的解决方案是添加:

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

并在fetchedInvoices的位置使用invoiceToView。

我的愚蠢错误!