Accessing objects in NSMutableDictionary by index

前端 未结 2 1287
忘掉有多难
忘掉有多难 2021-01-30 02:06

To display key/values from an NSMutableDictionary sequentially (in a tableview), I need to access them by index. If access by index could give the key at that index, I could th

2条回答
  •  既然无缘
    2021-01-30 02:52

    You can get an NSArray containing the keys of the object using the allKeys method. You can then look into that by index. Note that the order in which the keys appear in the array is unknown. Example:

    NSMutableDictionary *dict;
    
    /* Create the dictionary. */
    
    NSArray *keys = [dict allKeys];
    id aKey = [keys objectAtIndex:0];
    id anObject = [dict objectForKey:aKey];
    

    EDIT: Actually, if I understand what you're trying to do what you want is easily done using fast enumeration, for example:

    NSMutableDictionary *dict;
    
    /* Put stuff in dictionary. */
    
    for (id key in dict) {
        id anObject = [dict objectForKey:key];
        /* Do something with anObject. */
    }
    

    EDIT: Fixed typo pointed out by Marco.

提交回复
热议问题