我在viewDidLoad方法中运行此代码,以从Firebase提取数据以将其放入UIPageViewController

@interface MapViewController () <RoutesPageDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) RoutesPageViewController *routesPageViewController;
@property (weak, nonatomic) FIRFirestore *db;
@end

@implementation MapViewController

- (void) viewDidLoad {
    [super viewDidLoad];

    self.db = [FIRFirestore firestore];

    for (UIViewController *obj in self.childViewControllers) {
        if ([obj isKindOfClass:[RoutesPageViewController class]]) {
            self.routesPageViewController = (RoutesPageViewController *)obj;
            self.routesPageViewController.routesPageDelegate = self;
        }
    }

    FIRCollectionReference *routesRef = [self.db collectionWithPath:@"routes"];
    [routesRef getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot, NSError * _Nullable error) {
        if (error != nil) {
            // TODO: handle error
        } else {
            NSMutableArray<RouteModel*> *routes = [NSMutableArray array];

            // For each route
            for (FIRDocumentSnapshot *document in snapshot.documents) {
                RouteModel *route = [[RouteModel alloc] init];
                route.title = document.data[@"title"];
                route.color = document.data[@"color"];
                route.city = document.data[@"city"];

                [routes addObject:route];
            }

            [self.routesPageViewController setRoutes:routes];
        }
    }];


}

这就是所谓的setRoutes方法:
- (void) setRoutes:(NSMutableArray<RouteModel *> *)routes {
    self.routes = routes;

    NSMutableArray<RoutePageViewController *> * routeViewControllers = [NSMutableArray array];
    for (RouteModel * route in routes) {
        [routeViewControllers addObject:[self viewControllerAtIndex:[routes indexOfObject:route]]];
    }

    [self setViewControllers:routeViewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
}

执行setRoutes方法后,它将在下图中抛出错误,表示无法取消引用它:

ios - EXC_BAD_ACCESS objective-c 块-LMLPHP
setRoutes方法在一个块内执行。

我得到了这个奇怪的线程堆栈:
ios - EXC_BAD_ACCESS objective-c 块-LMLPHP

我该如何解决?

最佳答案

您的问题在这里:

- (void) setRoutes:(NSMutableArray<RouteModel *> *)routes {
    self.routes = routes;
隐式调用setter self.routes调用setRoutes会导致递归的无限调用,如堆栈所示。

09-27 00:06