希望NSArray valueForKey返回数组索引

时间:2011-12-22 01:32:22

标签: objective-c nsarray key-value-coding

我可以创建NSArray,其中包含myArray中对象的所有哈希值,如下所示:

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

我传递给valueForKey:以获取包含myArray索引的数组的密钥是什么?

说myArray有n个项目。我想做这样的事情:

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

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您可以使用indexOfObject:

在NSArray中查询对象的索引
NSArray *a = [myArray valueForKey:@"hash"];
NSInteger index = [myArray indexOfObject:a];

答案 2 :(得分:0)

创建一个NSArray的超类,它返回索引:

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

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