【问题标题】:How to get object index?如何获取对象索引?
【发布时间】:2025-12-24 02:05:11
【问题描述】:

如何获取我的对象索引?我有一个包含数组的字典,并且在数组中我有多个字典。

我的数据结构(例如):

学生 ------ NSDictionary

   Item 0 ------ NSArray<br>
          Name ----- Grace<br>
          Age ----- 20<br>
   Item 1 ------ NSArray<br>
          Name ----- Anne<br>
          Age ----- 21<br>             

例如,我有名称 Grace 的值,我想获取对象索引数组的值(在本例中为项目 0)。我该怎么做?

我使用了 indexOfObject,但是我得到的结果是 2147483647,我认为这意味着 nsnotfound。所以我认为它不适用于这种情况。

这是我的代码:

NSMutableDictionary* namevalue = [[NSMutableDictionary alloc] init];    
namevalue = [somedict objectForKey:@"Name"];              
int arryindex;
arryindex = [somearray indexOfObject:namevalue];                
NSLog(@"Array Index:%i", arryindex);

有人可以帮忙吗?非常感谢!

【问题讨论】:

    标签: iphone ios indexing nsmutablearray nsarray


    【解决方案1】:

    在您的代码中,您忘记包含 somedictsomearray 的创建。问题可能就在那里。

    此外,您无需为 namevalue 分配一个空字典,然后再分配数组中的实际字典。

    检查这段工作代码:

    NSUInteger idx;
    NSDictionary *john = [NSDictionary dictionaryWithObjectsAndKeys:@"John", @"name", 
                             [NSNumber numberWithInt:23], @"age", nil];
    NSDictionary *jane = [NSDictionary dictionaryWithObjectsAndKeys:@"Jane", @"name", 
                             [NSNumber numberWithInt:24], @"age", nil];    
    NSArray *students = [NSArray arrayWithObjects:john, jane, nil];
    idx = [students indexOfObject:john];
    NSLog(@"john is at: %i", idx == NSNotFound ? -1 : idx); /* 0 */
    idx = [students indexOfObject:jane];
    NSLog(@"jane is at: %i", idx == NSNotFound ? -1 : idx); /* 1 */
    

    现在,尝试使用数组中不存在的对象:

    NSDictionary *mary = [NSDictionary dictionaryWithObjectsAndKeys:@"Mary", @"name", 
                             [NSNumber numberWithInt:22], @"age", nil];        
    idx = [students indexOfObject:mary];
    NSLog(@"mary is at: %i", idx == NSNotFound ? -1 : idx); /* -1 Not found */
    

    最后是一个新对象,但创建为数组中已经存在的对象的精确副本:

    NSDictionary *maryjane = [NSDictionary dictionaryWithObjectsAndKeys:@"Jane", @"name", 
                                 [NSNumber numberWithInt:24], @"age", nil];            
    idx = [students indexOfObject:maryjane];
    NSLog(@"maryjane is at: %i", idx == NSNotFound ? -1 : idx); /* 1 */
    

    indexOfObject 方法将使用isEqual: 来比较对象。您可以验证新对象是否与数组中的对象相等:

    NSLog(@"jane is maryjane? %i", [jane isEqual:maryjane]); /* 1 */
    

    【讨论】:

    • 感谢您的回复(:somedict 是我的代码中有值的字典。我只是在此处添加了重要代码的 sn-p(:我不知道索引数组的“名称值”)想根据用户输入找到它。这就是为什么我想知道是否有办法通过“namevalue”检索对象索引(:
    【解决方案2】:

    如果我理解正确,您正在寻找一种方法来根据对象具有的属性值在 NSDictionary 中查找对象索引,对吧?
    例如。您的 students 字典中有一个名为 Grace 的学生,您想知道名为 Grace 的学生对象存储在哪个索引处...

    如果上述情况属实,这是我的(不完整且粗略的)解决方案,适用于具有 NSString 属性的对象,但一旦您了解以下想法,我认为您将能够修改代码以满足您的需求。

    - (NSInteger)indexOfObjectWithPropertyValue:(id)value inDictionary:(NSDictionary *)dict {
        NSInteger objectIndex = 0;
        unsigned int outCount, i;
    
        for (id key in dict) {
            id objForKey = [dict objectForKey:key];
            Class lender = [objForKey class];
    
            objc_property_t *properties = class_copyPropertyList(lender, &outCount);
    
            for (i = 0; i < outCount; i++) {
                objc_property_t property = properties[i];
                id v = [objForKey valueForKey:[NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding]];
    
                if ([v isKindOfClass:[value class]] && [v isEqual:value]) {
                    return objectIndex; 
                }
            }
            objectIndex++;
        }
    
        return NSNotFound; // i.e. NSIntegerMax
    }
    

    并且不要忘记包含运行时标头:

    #import <objc/runtime.h>
    

    我的代码可能存在一些问题:

    • 最明显的isEqual: 方法,需要比较属性的值。
    • 上面的代码没有涵盖当有许多具有相同值的对象的情况(比如许多同名的学生!)
    • ???

    我希望我的“答案”能让你更容易地实现你所需要的。

    【讨论】: