-1

以下代码让我发疯:

-(void)fetchEventDetails
{    
    NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://domain.com/ios/read.php"]];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];


    for(id object in dict){
    //NSLog(@"city : %@",object[@"city"]);
//        NSLog(@"title : %@",object[@"title"]);
//        NSLog(@"description : %@",object[@"description"]);
        [_eventsTitles addObject:object[@"title"]];
        [_eventsCity addObject:object[@"city"]];
    }


    NSLog(@"Array : %@", _eventsCity);
}

因此,如果我取消注释 for 循环的第一行,它会打印所有城市。如果我打印 NSArray,它显示为空。两者在.h 文件中的定义方式相同,即eventsTitles 和eventsCity。有什么问题?

谢谢您的帮助

4

2 回答 2

0

你在其他地方定义_eventsTitles_eventsCity

尝试这个:

-(void)fetchEventDetails
{    
    NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://domain.com/ios/read.php"]];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];

    _eventsTitles = [[NSMutableArray alloc] init];
    _eventsCity = [[NSMutableArray alloc] init];
    for(id object in dict){
    //NSLog(@"city : %@",object[@"city"]);
//        NSLog(@"title : %@",object[@"title"]);
//        NSLog(@"description : %@",object[@"description"]);
        [_eventsTitles addObject:object[@"title"]];
        [_eventsCity addObject:object[@"city"]];
    }


    NSLog(@"Array : %@", _eventsCity);
}
于 2013-03-26T20:44:12.683 回答
0

你有没有初始化self.eventsCityself.eventsTitlesNSMutableArrays?简单地将@properties它们声明为 `nil。

您也应该不将它们作为实例变量引用,而是作为self.arrayName. 您也可以通过这种方式进行惰性实例化,因此您不会遇到此问题 =)

编辑:添加惰性实例化代码,这样你就有了我的意思的例子:

- (NSMutableArray)eventsCity
{
    if (_eventsCity == nil)
       _eventsCity = [[NSMutableArray alloc] init];
    }
    return _eventsCity;
}

使用它,如果您在引用时还没有创建一个空数组,它将为您创建一个空数组self.eventsCity

于 2013-03-26T20:45:29.730 回答