OGeek|极客世界-中国程序员成长平台

标题: ios - Objective-c Json解析空数组错误还是Bug? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:07
标题: ios - Objective-c Json解析空数组错误还是Bug?

当我使用 tableview 解析 json 时,如果有 json 项目,但如果没有加载 json 项目,并且当我单击返回按钮时,会出现此错误。

erminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:

我认为当我单击快速后退按钮并在我的表格 View 代码下给出此错误时,json 不会加载。

    @interface MasterViewController ()

    @property (nonatomic, assign) NSInteger currentPage;
    @property (nonatomic, assign) NSInteger totalPages;
    @property (nonatomic, assign) NSInteger totalItems;
    @property (nonatomic, assign) NSInteger maxPages;

    @property (nonatomic, strong) NSMutableArray *activePhotos;
    @property (strong, nonatomic) NSMutableArray *staticDataSource;
    @property (nonatomic, strong) NSMutableArray *searchResults;

    @property (strong, nonatomic) IBOutlet UITableView *tableView;


    @end


            - (void)viewDidLoad
            {
                [super viewDidLoad];

                self.activePhotos = [[NSMutableArray alloc] init];
                self.searchResults = [[NSMutableArray alloc] init];
                self.staticDataSource = [[NSMutableArray alloc] init];


            }


            #pragma mark - Table View

- (NSInteger)tableViewUITableView *)tableView numberOfRowsInSectionNSInteger)section {

    return  self.activePhotos.count;
}



- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath
{
    UITableViewCell *cell;
    if (indexPath.row == [self.activePhotos count]) {
        cell = [self.tableView dequeueReusableCellWithIdentifier"LoadingCell" forIndexPath:indexPath];
        UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView *)[cell.contentView viewWithTag:100];
        [activityIndicator startAnimating];
    } else {
        NSDictionary *photoItem = self.activePhotos[indexPath.row];
        cell = [self.tableView dequeueReusableCellWithIdentifier"Cell" forIndexPath:indexPath];

        cell.textLabel.text = [photoItem objectForKey"name"];
        if (![[photoItem objectForKey"description"] isEqual:[NSNull null]]) {
            cell.detailTextLabel.text = [photoItem objectForKey"description"];
        }


    }


    return cell;
}



- (void)loadPhotosNSInteger)page
{



    NSString *userismim =[[NSUserDefaults standardUserDefaults] stringForKey"userisim"];


    NSArray* words = [userismim componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString* nospacestring = [words componentsJoinedByString""];


    NSLog(@"%@",nospacestring);


    NSString *apiURL = [NSString stringWithFormat"http://bla.com/server/table.php?user=%@",nospacestring];

    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:apiURL]
            completionHandler:^(NSData *data,
                                NSURLResponse *response,
                                NSError *error) {

                if (!error) {

                    NSError *jsonError = nil;
                    NSMutableDictionary *jsonObject = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];

                    NSLog(@"%@",jsonObject);

                    [self.staticDataSource addObjectsFromArray:[jsonObject objectForKey"photos"]];

                    self.currentPage = [[jsonObject objectForKey"current_page"] integerValue];
                    self.totalPages  = [[jsonObject objectForKey:@"total_pages"] integerValue];
                    self.totalItems  = [[jsonObject objectForKey:@"total_items"] integerValue];

                    self.activePhotos = self.staticDataSource;

                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.tableView reloadData];
                    });
                }
            }] resume];
}

感谢一切。我需要你的帮助。



Best Answer-推荐答案


您正在显示事件指示器,该指示器将一直旋转直到 json 加载。

如果您在 json 加载之前按下返回按钮,则会发生应用程序尝试为数组分配空引用,这是不可能的,因此会引发错误。

为避免这种情况,您可以在请求发出后停止 userInteraction,并仅在获得成功或失败响应后启用。

要禁用交互,请添加

[[UIApplication sharedApplicaton] beginIgnoringInteractionEvents]  

之后

NSURLSession *session = [NSURLSession sharedSession];

要再次启用,请添加:

 [[UIApplication sharedApplicaton] endIgnoringInteractionEvents]  

之前

if (!error) {

希望这能解决你的问题。

关于ios - Objective-c Json解析空数组错误还是Bug?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34019787/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4