How to copy custom NSObject into NSMutableArray

左心房为你撑大大i 提交于 2019-12-12 00:29:15

问题


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.

EDIT:

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

回答1:


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


来源:https://stackoverflow.com/questions/12296920/how-to-copy-custom-nsobject-into-nsmutablearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!