user6631314
user6631314

Reputation: 1958

IOS/Objective-C/Core data: Find index of an NSNumber in an array of NSManaged Objects

I perform a fetch from core data of nsmanaged objects. One of the attributes of the managed objects is an NSNumber, corresponding to the id of the objects (not Apple's objectid, my own sequential NSNumber id scheme). For a given object which has an id#, I would like to get the index of that object in the array. However, I can't figure out a way to get a list of the id#s as valueforkey does not work for nsnumbers and objectforkey throws an error with an nsmutablearray. Can anyone suggest how to do this?

Here is my non-working code. The problem is that I can't get a valid list of ids out of the fetched objects.

//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);

Upvotes: 0

Views: 169

Answers (1)

Matic Oblak
Matic Oblak

Reputation: 16774

You need to remap the objects into a new array. For straight forward something like:

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

This will result in array of ids as NSNumber objects only. Since NSNumber is an object the indexOfObject may not work. The reason is that it will compare pointers instead of values. So you will need to use compare method like:

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
    }
}

So in the end it is pretty much the same if you skip mapping your objects and simply compare it on the same object array:

    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
        }
    }

Upvotes: 1

Related Questions