如何获取NSManagedObjectId并检索数据

时间:2014-02-08 23:02:34

标签: ios xcode core-data uitableview

我有一个名为HomeTableViewController的TableViewController,它载有来自Core Data数组的数据。我试图从所选单元格中获取对象ID,如下所示:

//Fetch Entity

NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"OwedMoney"];

//Create an array that stores the contents of that entity

youOweArray = [[context executeFetchRequest:fetchRequest error:nil] mutableCopy];

//Create managedObjectId

NSManagedObject *YouOweData  = [youOweArray objectAtIndex:0];
NSManagedObjectID *moID = [YouOweData objectID];

//Successfully got the managedObjectId

NSLog(@"This is the id %@", moID);

我能够获得managedObjectId。但是这里遇到了困难的部分。现在我想迭代我的数组并获取所有对象。然后我想得到等于所选单元格的对象并访问它的布尔值“付费”。我这样做了:

 BOOL Found =  NO;
OwedMoney *OwedObject;
NSManagedObjectID *OwedId = [OwedObject objectID];

for (OwedMoney *OwedObject in youOweArray)
{

    NSLog(@"%@", OwedObject);
    if (OwedId == moID)
    {
        Found = YES;
        break;
    }

}

if (Found == YES)
{

BOOL isPaid = YES;
OwedMoney *Object = OwedObject;
Object.paid = [NSNumber numberWithBool:isPaid];

NSLog(@"Is it paid: %@",Object.paid? @"Yes":@"No");
}

虽然当我运行应用程序时,Found永远不会等于YES。这意味着我的对象Id不匹配。我想知道如何找到所选的表视图单元格,从中获取NSManagedObjectId,然后访问它的属性。

所有帮助表示赞赏,提前致谢。

2 个答案:

答案 0 :(得分:1)

您正在循环遍历数组,但实际上从未将OwedId更改为您在数组中查看的项目。这应该有效:

BOOL Found =  NO;
OwedMoney *Object;


for (OwedMoney *OwedObject in youOweArray)
{
    NSManagedObjectID *OwedId = [OwedObject objectID];

    NSLog(@"%@", OwedObject);
    if (OwedId == moID)
    {
        Found = YES;
        Object = OwedObject;
        break;
    }

}

if (Found)
{

    BOOL isPaid = Found;
    Object.paid = [NSNumber numberWithBool:isPaid];

    NSLog(@"Is it paid: %@",Object.paid.boolValue? @"Yes":@"No");
}

答案 1 :(得分:0)

我认为问题出在第9行。

if(OweID == moID)

可能是托管对象的ID对象(不是ID信息本身)发生了变化。使用==仅比较引用。尝试使用

if([OweID isEqual::moID])

托马斯