SundayMonday
SundayMonday

Reputation: 19767

Would like NSArray valueForKey to return the array indices

I can create an NSArray that contains all the hash values of the objects in myArray like this:

NSArray *a = [myArray valueForKey:@"hash"];

What key do I pass to valueForKey: to get an array containing myArray's indices?

Say myArray has n items. I'd like to do something like this:

NSArray *a = [myArray valueForKey:@"index"];

Upvotes: 1

Views: 3230

Answers (3)

carmin
carmin

Reputation: 419

Create a superclass of NSArray which returns the index:

//
//  CapArrayOfIndex.h
//  Created by carmin politano on 7/26/12.
//  no rights reserved
//

@interface CapArrayOfIndex : NSArray {
    /*! Simulated constant array containing an array of NSNumber representing the index. */
    NSUInteger iCount;
    //*! NSNotFound causes bybass of index bounds testing. */
}
#pragma mark create
+ (CapArrayOfIndex*) withCount: (NSUInteger) aCount;
@end

and

//
//  CapArrayOfIndex.mm
//  Created by carmin on 7/26/12.
//  no rights reserved
//

#import "CapArrayOfIndex.h"

@implementation CapArrayOfIndex
#pragma mark NSCopying
- (id) copyWithZone: (NSZone*) aZone {
    /*! New allocation required because -count is a mutable property. */
    return [CapArrayOfIndex withCount: self.count];
}
#pragma mark create
+ (CapArrayOfIndex*) withCount: (NSUInteger) aCount {
    CapArrayOfIndex* zArray = self.alloc;
    zArray->iCount = aCount;
    return zArray;
}
#pragma mark NSArray
- (NSUInteger) count {
    return iCount;
}
- (void) setCount: (NSUInteger) aCount {
    iCount = aCount;
}
- (id) objectAtIndex: (NSUInteger) aIndex {
    /*! My code performs a bounds test using unusual macros: return [ViaUInteger RaiseIfObjectAtIndex(nil, self, aIndex, nil)]; */
    return [NSNumber numberWithInteger: aIndex];
}
@end

Upvotes: 0

jscs
jscs

Reputation: 64022

NSArray * arrayWithNumbersInRange( NSRange range )
{
    NSMutableArray * arr = [NSMutableArray array];
    NSUInteger i;
    for( i = range.location; i <= range.location + range.length; i++ ){
        [arr addObject:[NSNumber numberWithUnsignedInteger:i];
    }

    return arr;
}

NSArray * indexArray = arrayWithNumbersInRange((NSRange){0, [myArray length]-1});

Upvotes: 2

Jessedc
Jessedc

Reputation: 12470

You can query an NSArray for the index of an object with indexOfObject:

NSArray *a = [myArray valueForKey:@"hash"];
NSInteger index = [myArray indexOfObject:a];

Upvotes: 1

Related Questions