EXC_BAD_ACCESS objective-c块

问题描述 投票:1回答:2

我在我的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方法被执行时,它会在下面的图像中抛出错误,说它无法取消引用它:

enter image description here

setRoutes方法在块内执行。

我得到这个奇怪的线程堆栈:enter image description here

我怎么解决这个问题?

ios objective-c firebase block
2个回答
2
投票

你的问题在这里:

- (void) setRoutes:(NSMutableArray<RouteModel *> *)routes {
    self.routes = routes;

调用qazxsw poi隐式调用setter qazxsw poi,它会导致堆栈指示的递归无限调用。


1
投票

当块传递到self.routes方法执行时,setRoutes数组已经被释放并设置为getDocumentsWithCompletion,因为没有人将它保留在块外的任何地方。

您应该将其移动到块中或将其声明为类属性,以便在类实例处于活动状态时不会将其抛出内存。

routes

更新后:

nil会调用[routesRef getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) { NSMutableArray<RouteModel*> *routes = [NSMutableArray array]; ... [self.routesPageViewController setRoutes:routes]; }]; ,而self.routes = routes会导致代码中出现循环。您应该将其更改为:

setRoutes:
© www.soinside.com 2019 - 2024. All rights reserved.