IOS / Objective-C / Core数据:在NSManaged Objects数组中查找NSNumber的索引

时间:2017-08-09 14:03:04

标签: ios core-data indexof

我从nsmanaged对象的核心数据执行提取。管理对象的一个​​属性是NSNumber,对应于对象的id(不是Apple的objectid,我自己的顺序NSNumber id方案)。对于具有id#的给定对象,我想获取该对象在数组中的索引。但是,我无法找到获取id #s列表的方法,因为valueforkey对nsnumbers不起作用,而objectforkey会使用nsmutablearray抛出错误。谁能建议怎么做?

这是我的非工作代码。问题是我无法从获取的对象中获取有效的ID列表。

//FETCH ITEMS
- (id) getItems{

    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Items"];
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"lasttouched" ascending:NO];
    [fetchRequest setSortDescriptors:@[sort]];
    NSError *error      = nil;
    self.managedObjectContext = [IDModel sharedInstance].managedObjectContext;

    NSArray *results    = [self.managedObjectContext executeFetchRequest:fetchRequest
     NSMutableArray *mutableresults = [results mutableCopy];
    [mutableresults removeObjectIdenticalTo:[NSNull null]];
    NSArray*someids =[[mutableresults valueForKey:@"myid"] mutableCopy];
//THIS IS EMPTY WHEN LOGGED
    _someids = someids;//save to ivar
         return mutableresults; //an array of activity objects with all their properties
    }

    // In method to get index of the object

     NSInteger myIndex=[_someids indexOfObject:@33];
        NSLog(@"anIndex%ld",(long)anIndex);

1 个答案:

答案 0 :(得分:1)

您需要将对象重新映射到新数组中。对于直接的事情:

NSMutableArray *arrayOfIdentifiers = [[NSMutableArray alloc] init];
for(WhateverMyManagedObjectIs *item in results) { if(item.myid) [arrayOfIdentifiers addObject:item.myid]; }

这将导致仅作为NSNumber个对象的id数组。由于NSNumber是一个对象,indexOfObject可能无效。原因是它将比较指针而不是值。因此,您需要使用compare方法,例如:

NSInteger index = -1;
for(NSInteger i=0; i<_someids.count; i++) {
    if([_someids[i] compare:@33] == NSOrderedSame) {
        index = i; 
        break; // Break after first one is found
    }
}

所以最后,如果你跳过映射你的对象并简单地在相同的对象数组上进行比较,它几乎是一样的:

    NSInteger index = -1;
    for(NSInteger i=0; i<results.count; i++) {
        if([[results[i] myid] compare:@33] == NSOrderedSame) {
            index = i; 
            break; // Break after first one is found
        }
    }