0

我是 iPhone 新手,我想将元素添加到 NSMutableArray 中,每个元素的名称为我为 keys 创建了一个 MutableArray,然后为我从名为 Pages 的对象中获取的元素创建了另一个数组。

我写了以下代码

NSMutableArray *myArray;


NSMutableArray *arrayKey = [[NSMutableArray alloc] initWithObjects:@"b_pag_id", @"b_pag_bo_id", @"b_pag_num", @"b_pag_note", @"b_page_mark", @"b_page_stop", @"b_pag_user_id", nil];

    for (int x=0; x<[pages count]; x++) {
        Pages *myPages = (Pages *)[self.pages objectAtIndex:x];

        NSString *b_pag_id2 = [NSString stringWithFormat:@"%d",myPages.b_pag_id];
        NSString *b_pag_bo_id2 = [NSString stringWithFormat:@"%d",myPages.b_pag_bo_id];
        NSString *b_pag_num2 = [NSString stringWithFormat:@"%d",myPages.b_pag_num];
        NSString *b_pag_note2 = myPages.b_pag_note;
        NSString *b_page_mark2 = [NSString stringWithFormat:@"%d",myPages.b_page_mark];
        NSString *b_page_stop2 = [NSString stringWithFormat:@"%d",myPages.b_page_stop];
        NSString *b_pag_user_id2 = [NSString stringWithFormat:@"%d",myPages.b_pag_user_id];

        NSMutableArray *arrayValue = [[NSMutableArray alloc] initWithObjects:b_pag_id2, b_pag_bo_id2, b_pag_num2, b_pag_note2, b_page_mark2, b_page_stop2, b_pag_user_id2, nil];

        NSDictionary *theReqDictionary = [NSDictionary dictionaryWithObjects:arrayValue forKeys:arrayKey];

        myArray = [NSMutableArray arrayWithObjects:theReqDictionary,nil];
    }

   NSLog(@"array size: %d", [myArray count]);

我想将每个元素添加到它的键中,例如元素 (b_pag_id2) 它的键 (b_pag_id) ..etc 这是对的吗?或如何做到这一点?考虑到 NSLog(@"array size: %d", [myArray count]); 给我 1 我元素的大小是 14

4

3 回答 3

2

在循环之前,您需要初始化 aray

NSMutableArray *myArray = [NSMutableArray array];

在循环内替换以下内容:

myArray = [NSMutableArray arrayWithObjects:theReqDictionary,nil];

[myArray addObject:theReqDictionary];

问题是您在每次循环迭代中创建一个包含 1 个字典的新数组。相反,您需要初始化数组并一一添加值。

于 2012-05-29T12:01:14.803 回答
0

每次通过您的循环时,您都会为其创建一个myArray只有一个元素的新数组。您应该在循环之前初始化一个空的 NSMutableArray,然后简单地将新对象添加到其中,而不是使用arrayWithObjects:to create myArray..

于 2012-05-29T11:42:37.280 回答
0

这里我举一个简短的例子,希望对你有所帮助。看到这个代码: -

NSMutableArray *arrayValue = [[NSMutableArray alloc]initWithObjects:@"Value1",@"Value2",@"Value3", nil];
NSMutableArray *arrayKey = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3", nil];

NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];

for(int i=0;i<3;i++)
{
    [dic setObject:[arrayValue objectAtIndex:i] forKey:[arrayKey objectAtIndex:i]];
}

//and you can see this by printing it using nslog-

NSLog(@"%@",[dic valueForKey:@"1"]);

谢谢!!!

于 2012-05-29T12:52:26.597 回答