【问题标题】:Why is my NSArray turning into an NSSet?为什么我的 NSArray 变成了 NSSet?
【发布时间】:2012-05-27 16:44:14
【问题描述】:

在 Objective-C 中,我使用核心数据获取实体,并将它们作为 NSArrays 返回。我意识到我获取的频率太高了,我可以利用实体​​的返回值,例如:客户实体有很多 Invoices,Invoices 有很多 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

【问题讨论】:

  • Price 是什么类型的属性?
  • 你确定吗?在您的行前尝试NSLog ([[[fetchedObjects objectAtIndex:i] valueForKey:@"Price"] class];,其中包含doubleValue
  • 你能给我们看看 Invoices.h 吗?

标签: objective-c core-data nsarray nsset


【解决方案1】:

尝试这样做:

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

确定你得到什么类型。

【讨论】:

  • 所以我得到:class name: __NSCFSet 2012-05-27 13:10:26.379 InventoryProgram[57463:707] {( 399, 499 )},但我的核心数据模型将其建模为 NSNumber,在我的标题中我有:@property (nonatomic, retain) NSNumber * Price;
  • 尝试从设备/模拟器中删除应用程序,然后清理并再次运行。只是为了确保您的模型与持久存储匹配。我知道它会抛出不同的异常,但请试一试。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

    并使用 invoiceToView 代替 fetchedInvoices。

    我犯了一个愚蠢的错误!

    【讨论】:

    • 是的,你问题中的 self.fetchedInvoices 是一个 NSSet 数组:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    相关资源
    最近更新 更多