问题
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