将数组中的对象添加到字典中

时间:2012-07-30 17:56:03

标签: objective-c ios arrays dictionary

我从SQLite DB获取行并尝试将它们插入到字典中。除了我不断收到错误!我得到错误“使用ARC禁止将Objective-C指针隐式转换为'const id *'”我知道这意味着当我向字典中添加对象时我无法使用指针。那么我该如何修复它以便将这些数组添加到字典中呢?

    NSArray *keyArray = [[NSMutableArray alloc] init ];
    NSArray *valueArray = [[NSMutableArray alloc ] init ];
    NSDictionary* dic;
    NSInteger dataCount = sqlite3_data_count(statement);
    while (sqlite3_step(statement) == SQLITE_ROW) {
        @try {
            for (int i = 0; i < dataCount; i ++)
            {
                NSString* key = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, i)];  
                NSString *value = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, i)];

                if ([value length] == 0)
                {
                    value = @"";
                }

                keyArray = [keyArray arrayByAddingObject:key];
                valueArray = [valueArray arrayByAddingObject:value];

            }

        }
        @catch (NSException *ex)
        {
            NSLog(@"%@,%@", [ex name], [ex reason]);
        }

        dic= [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray count:[keyArray count]];

2 个答案:

答案 0 :(得分:5)

dictionaryWithObjects:forKeys:count:采用C风格的数组,而不是NSArray个对象。 dictionaryWithObjects:forKeys:可以解决这个问题,但你可能最好还是在你完全绕过NSArray时构建一个可变字典。

NSDictionary* dic;
NSMutableDictionary *tmp = [NSMutableDictionary dictionary];

for (int i = 0; i < dataCount; i ++)
{
    NSString* key = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, i)];  
    NSString *value = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, i)];
    [tmp setObject:value forKey:key];
}
dict = tmp;

答案 1 :(得分:0)

[dicBodyPost setValue:arrContactAddress forKey:@“contactAddress”];