NSMictionary的NSMutableArray

时间:2015-02-08 21:12:19

标签: ios objective-c nsmutablearray

我在NSDictionaries内有多个NSMutableArray。下面是一个简短的例子。 comparisonChartNSMutableArray

NSDictionary *dict1 = @{
                       @"Tube": @"10/0",
                       @"Dress":@"3"
                       };

[self.comparisonChart setValue:dict1 forKey@"0"];
// key 0 as i wish to use numeric indexes, comparisonChart is mutable array

当我希望提取我尝试过的密钥的值时:

[self.comparisonChart valueForKey:[NSString stringWithFormat:@"%ld", value]]
//where value is numeric value e.g 0

但是这会返回null。香港专业教育学院也尝试objectForKey:value同样的结果。

我该怎么做?

更新

[self.comparisonChart insertObject:dict23 atIndex:1];

NSLog(@"chart: %@", [self.comparisonChart objectAtIndex:1]);

Output: chart: (null)   // why is this?

2 个答案:

答案 0 :(得分:1)

如果self.comparisonChart是NSMutableArray,那么你就像这样添加NSDictionary:

[self.comparisonChart addObject: dict1];

或者您可以像这样指定索引:

[self.comparisonChart insertObject: dict1 atIndex:desiredIndex];

要检索NSDictionary对象,您必须调用:

[self.comparisonChart objectAtIndex:indexNumber];

答案 1 :(得分:0)

你需要使用objectForKey,你也应该使用下标;

NSDictionary *dict1 = @{@"Tube": @"10/0",
                       @"Dress":@"3"};

NSMutableDictionary *comparisonChart = [NSMutableDictionary new];
comparisonChart[@"0"] = dict1;

NSLog(@"My value: %@", comparisonChart[@"0"]);

这是代码副本并从AppDelegate粘贴并正常工作:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSDictionary *dict1 = @{@"Tube": @"10/0",
                            @"Dress":@"3"};

    NSMutableDictionary *comparisonChart = [NSMutableDictionary new];
    comparisonChart[@"0"] = dict1;

    NSLog(@"My value: %@", comparisonChart[@"0"]);

    return YES;
}

编辑:

要附加上述问题,请确保根据以下文档插入的索引有效:

Apple documentation

- (void)insertObject:(id)anObject
             atIndex:(NSUInteger)index
Parameters
anObject  
The object to add to the array's content. This value must not be nil.
IMPORTANT
Raises an NSInvalidArgumentException if anObject is nil.
index 
The index in the array at which to insert anObject. This value must not be greater than the count of elements in the array.
IMPORTANT
Raises an NSRangeException if index is greater than the number of elements in the array.
Discussion
If index is already occupied, the objects at index and beyond are shifted by adding 1 to their indices to make room.

Note that NSArray objects are not like C arrays. That is, even though you specify a size when you create an array, the specified size
     

被视为“暗示”;数组的实际大小仍为0.这个   意味着您不能在大于的索引处插入对象   数组的当前计数。例如,如果数组包含两个   对象,其大小为2,因此您可以在索引0,1或2处添加对象。   指数3是非法的,不受限制;如果你试图添加一个对象   索引3(当数组的大小为2时),NSMutableArray引发一个   异常。

Import Statement
import Foundation

Availability
Available in iOS 2.0 and later.