iOS 5将NSDictionary转换为NSMutableArray的问题?

时间:2012-03-01 00:29:38

标签: ios5 nsmutablearray nsdictionary ipod

我正在创建一个IPOD应用程序,我有一个我从JSON提要创建的NSDictionary。我试图将其转换为NSMutableArray。我知道我需要遍历字典并将键和值写入数组但我遇到了代码问题。这是实现这一目标的方法。

////从网站获取JSON数据     NSError *错误;     NSDictionary * json = [NSJSONSerialization JSONObjectWithData:数据选项:kNilOptions错误:& error];

////// convert the dictionary to an NSMutableArray
// create an empty array of size equal to the number of json records
NSMutableArray *users = [[NSMutableArray alloc] initWithCapacity:1];                           
//  Begin filling the array
NSInteger dCount = [json count];

for(int i=0; i <  dCount; i++)
{
    User *user = [[User alloc] init];
    user.emailAddress = [json objectForKey: @"emailAddress"];
    user.password = [json objectForKey: @"password"];
    user.password = [json objectForKey: @"password"];
    [users addObject:user];
    NSLog(@"This is record: %@", i);

}

提前致谢。

1 个答案:

答案 0 :(得分:0)

好吧可能不是最优雅的解决方案,但有很多帮助,这就是我想出来的:

////////////////在服务上构建用户数组     dispatch_queue_t bgQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);     dispatch_async(bgQueue,^ {

////// Building users list
//Get the data from the webserver 
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://msis-discussion-forum.appspot.com/users"]];

NSLog(@"Beginning to build array");
////   Get the JSON data from the website
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"This is my JSON data %@", json);
usersArray =[[NSMutableArray alloc]init];
NSArray *userJSONObjects = [json objectForKey:@"users"];
for (User *tempUser in userJSONObjects)
{
    User *user = [[User alloc] init];
    user.displayName = [tempUser valueForKey:@"displayName"];
    NSLog(@"%@",user.displayName);
    user.emailAddress = [tempUser valueForKey:@"emailAddress"];
    NSLog(@"%@",user.emailAddress);
    user.password = [tempUser valueForKey: @"password"];
    NSLog(@"%@",user.password);
    [usersArray addObject:user];
} 
 }); 

希望它有所帮助。