如何将自定义NSObject复制到NSMutableArray [英] How to copy custom NSObject into NSMutableArray

查看:71
本文介绍了如何将自定义NSObject复制到NSMutableArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NSDictionary* json = [NSJSONSerialization
                      JSONObjectWithData:responseData 

                      options:kNilOptions
                      error:&error];
NSArray* users = [json objectForKey:@"Users"];
NSEnumerator* enumerator = [users objectEnumerator];
id element;
NSMutableArray *results;
Result *fetchedResults;
while(element = [enumerator nextObject]) {

   // fetchedResults = [[Result alloc] init]; // i have tried commenting/uncommenting
    fetchedResults.name = (NSString *)[[element objectForKey:@"User"] objectForKey:@"name"];
    fetchedResults.email = (NSString *)[[element objectForKey:@"User"] objectForKey:@"name"];
    NSLog(@"%@", fetchedResults.name);
    [results addObject:fetchedResults];

    NSLog(@"%@", (NSString *)[[element objectForKey:@"User"] objectForKey:@"name"]); // this returns valid dump

}
NSLog(@"%d", [results count]); // returns 0

我不明白这里错了.我搜索了许多教程,并且资源似乎在这里没错.

I don't understand wht's wrong here. I have searched through numerous tutorials and resources don't seem to get what's wrong here.

NSLog(@"%@", fetchedResults.name); // dumps null

推荐答案

您忘记分配结果数组NSMutableArray *results = [[NSMutableArray alloc] init],这应该会有所帮助.

You forgot to allocate your results array NSMutableArray *results = [[NSMutableArray alloc] init] this should help.

NSDictionary* json = [NSJSONSerialization
                  JSONObjectWithData:responseData 
                  options:kNilOptions
                  error:&error];
NSArray* users = [json objectForKey:@"Users"];
NSMutableArray *results = [[NSMutableArray alloc] init];

for (id object in users) {
    Result *fetchedResults = [[Result alloc] init];
    fetchedResults.name = (NSString *)[[element objectForKey:@"User"] objectForKey:@"name"];
    fetchedResults.email = (NSString *)[[element objectForKey:@"User"] objectForKey:@"name"];
    NSLog(@"%@", fetchedResults.name);
    [results addObject:fetchedResults];
}



NSLog(@"%@", (NSString *)[[element objectForKey:@"User"] objectForKey:@"name"]);
}

NSLog(@"%d", [results count]); // returns 0

这篇关于如何将自定义NSObject复制到NSMutableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆