如何根据另一个数组中的值向NSMutableArray添加索引?

时间:2015-08-03 07:39:33

标签: ios objective-c arrays

我看过很多关于NS(Mutable)阵列的问题。我想我不是在理解这个概念,或者这些问题看起来并不相关。

我'试图做的是:

传入阵列1:

名称 码 开始时间 时间结束 等

传入阵列2

代码 序

我想要的是什么:

序 名称 码 开始时间 时间结束 等

这是我目前的代码:

int i=0;
for (i=0; i < stationListArray.count; i++) {
    NSString *slCodeString = [stationListArray[i] valueForKey:@"Code"];
    NSLog(@"slCodeString: %@", slCodeString);
    int j=0;
    for (j=0; j< lineSequenceArray.count; j++) {
        NSString *lsCodeString = [lineSequenceArray[j]valueForKey:@"StationCode"];
        NSLog(@"lsCodeString: %@", lsCodeString);
        if ([slCodeString isEqualToString:lsCodeString]) {
            NSLog(@"match");
            NSString *ordinalString = [lineSequenceArray[j] valueForKey:@"SeqNum"];
            NSLog(@"ordinalString: %@", ordinalString);
            [stationListArray[i] addObject:ordinalString]; <------
        }
    }
}

我记录了值并正确返回。 编译器不喜欢最后一个语句。我收到这个错误:

[__NSCFDictionary addObject:]: unrecognized selector sent to instance 0x7f9f63e13c30
 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary addObject:]: unrecognized selector sent to instance 0x7f9f63e13c30'

以下是StationListArray的摘录:

(
        {
        Address =         {
            City = Greenbelt;
            State = MD;
            Street = ".....";
            Zip = 20740;
        };
        Code = E10;
        Lat = "39.0111458605";
        Lon = "-76.9110575731";
        Name = Greenbelt;
    }   
)

2 个答案:

答案 0 :(得分:3)

        NSString *ordinalString = [lineSequenceArray[j] valueForKey:@"SeqNum"]; //Is NSString
        [stationListArray[i] addObject:ordinalString];//<----- trying to call addObject method of NSMutableArray on NSDictionary -> Not GOOD 

当您执行[stationListArray[i]时,您会得到NSDictionary (通常它返回NSObject位于给定索引的NSArray内,在您的情况下为NSDictionary)。

因此,为了完成您想要的操作:您应该制作NSMutableDictionary个实例(在这种情况下,它应该是来自mutableCopy的{​​{1}}的{​​{1}}是stationListArray[i],当您执行NSObject时,它会复制整个NSDictionary并使其成为mutableCopy) 对其进行更改,然后将其分配到NSDictionary

例如:

Mutable

答案 1 :(得分:1)

            [stationListArray[i] addObject:ordinalString]; <------

这不是NSMutableArray。你必须使用

            [stationListArray addObject:ordinalString]; <------

而不是你所做的。

以下是编写更易理解的代码的方法,因为对我来说代码不清楚。你也可以在循环中尝试这样做以实现你想要的。

NSMutableArray *array = [NSMutableArray new];
NSMutableDictionary *dictMain = [NSMutableDictionary new];
NSMutableDictionary *dictAddress = [NSMutableDictionary new];

[dictAddress setValue:@"Greenbelt" forKey:@"City"];
[dictAddress setValue:@"MD" forKey:@"State"];
[dictAddress setValue:@"....." forKey:@"Street"];
[dictAddress setValue:@"20740" forKey:@"Zip"];

[dictMain setValue:dictAddress forKey:@"Address"];
[dictMain setValue:@"E10" forKey:@"Code"];
[dictMain setValue:@"39.0111458605" forKey:@"Lat"];
[dictMain setValue:@"-76.9110575731" forKey:@"Lon"];
[dictMain setValue:@"Greenbelt" forKey:@"Name"];

[array addObject:dictMain];