为什么我的NSArray变成了NSSet



在Objective-C中,我使用核心数据获取实体,它们作为NSArrays返回。我意识到我获取得太频繁了,我可以利用实体的返回值,例如:客户实体有许多发票,发票有许多已售出的物品。这是我正在使用的一些代码:

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

尝试这样做:

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

以确保您获得哪种类型。

[fetchedObjects objectAtIndex:i] 在这里似乎是一个 NSSet。[[fetchedObjects objectAtIndex:i] valueForKey:@"Price"] 将获取所有带有键 "Price" 的对象,它是一个 NSSet。祝你好运!

我意识到了我的错误。我正在将获取的客户分类到特定的"客户到视图"中。我没有对我获取的发票做同样的事情。所以我的解决方案是添加:

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

并使用 invoiceToView 代替提取的发票。

我的愚蠢错误!

最新更新