2011-11-05 55 views
2

我有一个NSMutableArray初始化为10个元素。出生时,我设法得到它运行异常的元素的问题..valueForKey上的NSMutableArray异常

我以这种方式创建数组:

NSMutableArray *selected = [[NSMutableArray alloc] init]; 
    [selected setValue:[NSString stringWithFormat:@"casa_selected.png"]forKey:[NSString stringWithFormat:@"%d",1]]; 
    [selected setValue:[NSString stringWithFormat:@"chiave_selected.png"]forKey:[NSString stringWithFormat:@"%d",2]]; 
    [selected setValue:[NSString stringWithFormat:@"gatto_selected.png"]forKey:[NSString stringWithFormat:@"%d",3]]; 
    [selected setValue:[NSString stringWithFormat:@"giacca_selected.png"]forKey:[NSString stringWithFormat:@"%d",4]]; 
    [selected setValue:[NSString stringWithFormat:@"nonno_selected.png"]forKey:[NSString stringWithFormat:@"%d",5]]; 
    [selected setValue:[NSString stringWithFormat:@"lumaca_selected.png"]forKey:[NSString stringWithFormat:@"%d",6]]; 
    [selected setValue:[NSString stringWithFormat:@"cane_selected.png"]forKey:[NSString stringWithFormat:@"%d",7]]; 
    [selected setValue:[NSString stringWithFormat:@"occhiali_selected.png"]forKey:[NSString stringWithFormat:@"%d",8]]; 
    [selected setValue:[NSString stringWithFormat:@"portafogli_selected.png"]forKey:[NSString stringWithFormat:@"%d",9]]; 
    [selected setValue:[NSString stringWithFormat:@"telecomando_selected.png"]forKey:[NSString stringWithFormat:@"%d",10]]; 

当我试图让元素:

[selected valueForKey:[NSString stringWithFormat:@"%d",2]] 

它运行此例外:

2011-11-05 10:04:37.426 TrovaChiavi[22307:11f03] -[__NSArrayI isEqualToString:]: 
unrecognized selector sent to instance 0x78317b0 
2011-11-05 10:04:37.494 TrovaChiavi[22307:11f03] *** Terminating app due to uncaught 
exception 'NSInvalidArgumentException', reason: '-[__NSArrayI isEqualToString:]: 
unrecognized selector sent to instance 0x78317b0' 
*** First throw call stack: 
(0x1e01052 0x1343d0a 0x1e02ced 0x1d67f00 0x1d67ce2 0x39c68f 0x630ece 0x63eb6e 0x63f13f 0x9258 
0x32464e 0x4e2f 0x1e02ec9 0x2615c2 0x26155a 0x306b76 0x30703f 0x3062fe 0x286a30 0x286c56 
0x26d384 0x260aa9 0x16e9fa9 0x1dd51c5 0x1d3a022 0x1d3890a 0x1d37db4 0x1d37ccb 0x16e8879 
0x16e893e 0x25ea9b 0x26ed 0x2665) 
terminate called throwing an exception[Switching to process 22307 thread 0x11f03] 

回答

5

对键/值关联使用NSMutableDictionary。 NSMutableArray用于基于索引的存储/访问。

+1

特别是,NSArray定义了'valueForKey:'和'setValue:forKey:'来完成与大多数类非常不同的事情。 – Chuck