[NSURL initFileURLWithPath:]: ноль строковый параметр при попытке загрузить представление - PullRequest
0 голосов
/ 11 января 2012

Когда мое представление пытается загрузить, приложения аварийно завершают работу, и я получаю этот стек:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'

Это мой код, я действительно не знаю, где искать, когда происходит этот сбой:

#import "Itineraire.h"
#import "SBMapView.h"
#import "SBRouteAnnotation.h"
#import "City.h"
#import "UICGRoutes.h"
#import "SBCheckPointViewController.h"
//#import "SBRouteDetailView.h"

@interface Itineraire(Private)
-(void)customInitialization;
@end

@implementation Itineraire(Private)

-(void)customInitialization
{
    // do the initialization of class variables here..

    mDirections          = [UICGDirections sharedDirections];
    mDirections.delegate = self;
}

@end

@implementation Itineraire

@synthesize map             = mMap;
@synthesize startPoint      = mStartPoint;
@synthesize endPoint        = mEndPoint;
@synthesize loadBtn     = mLoadBtn;
@synthesize annotationArray = mAnnotationArray;
@synthesize travelMode      = mTravelMode;
@synthesize destination;
@synthesize routes;
@synthesize mAnnotations;
@synthesize mRouteArray;
@synthesize mRouteDetail;

//Invoked when the class is instantiated in XIB
-(id)initWithCoder:(NSCoder*)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if( self)
    {
        [self customInitialization];
    }
    return self;
}

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        [self customInitialization];
    }
    return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Google Maps";
    self.map = [[SBMapView alloc] initWithFrame:CGRectMake(0, 49, self.view.frame.size.width, self.view.frame.size.height)];
    //self.map = [[SBMapView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 381)];

    [self.view addSubview:mMap];

    self.view.backgroundColor = [UIColor blackColor];
    self.annotationArray = [[NSMutableArray alloc]init];
    self.routes          = [[UICGRoutes alloc]init];


    if (mDirections.isInitialized) {
        [self updateRoute];
    }
}
/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];

}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];

}
- (void)viewWillDisappear:(BOOL)animated; 
{
    [super viewWillDisappear:YES];

}

#pragma mark -
#pragma mark Instance Methods

- (void)updateRoute
{   /*
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
     UICGDirectionsOptions *options = [[[UICGDirectionsOptions alloc] init] autorelease];
     options.travelMode = mTravelMode;
     City *mFirstCity = [[[City alloc]init] autorelease];
     mFirstCity.mCityName = @"Paris";//mStartPoint;
     //[mDirections loadWithStartPoint:mFirstCity.mCityName endPoint:destination options:options];
     //added
     NSMutableArray * DestinationCityArray = [[NSMutableArray alloc]init];
     [DestinationCityArray addObject:@"Berlin"];
     [mDirections loadWithStartPoint:mFirstCity.mCityName endPoint:destination options:options];
     */
    //
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    UICGDirectionsOptions *options = [[UICGDirectionsOptions alloc] init] ;
    options.travelMode = mTravelMode;
    City *mFirstCity = [[City alloc]init];
    mFirstCity.mCityName = @"Amsterdam";//mStartPoint;
    NSMutableArray *dest=[[NSMutableArray alloc]init];
    [dest addObject:@"Berlin"];
    [mDirections loadWithStartPoint:mFirstCity.mCityName endPoint:dest options:options];


}

-(void)loadRouteAnnotations
{
    self.mRouteArray = [mDirections routeArray];
    NSLog(@"mRouteArray %@",mRouteArray);
    self.mAnnotations = [[NSMutableArray alloc]init];
    for (int idx = 0; idx < [mRouteArray count]; idx++) {
        NSArray *_routeWayPoints1 = [[mRouteArray objectAtIndex:idx] wayPoints];
        NSArray *mPlacetitles = [[mRouteArray objectAtIndex:idx] mPlaceTitle]; 
        self.annotationArray = [NSMutableArray arrayWithCapacity:[_routeWayPoints1 count]-2];

        mLoadBtn.title = @"OFF";
        mLoadBtn.target = self;
        mLoadBtn.action = @selector(removeRouteAnnotations);

        for(int idx = 0; idx < [_routeWayPoints1 count]-1; idx++)
        {

            mBetweenAnnotation = [[SBRouteAnnotation alloc] initWithCoordinate:[[_routeWayPoints1 objectAtIndex:idx]coordinate]
                                                                          title:[mPlacetitles objectAtIndex:idx]
                                                                 annotationType:SBRouteAnnotationTypeWayPoint];
            [self.annotationArray addObject:mBetweenAnnotation];
        }
        [mAnnotations addObject:mAnnotationArray];
        [self.map.mapView addAnnotations:[mAnnotations objectAtIndex:idx]];
        NSLog(@"map %@",mMap);

    }   
}

-(void)showCheckpoints
{
    SBCheckPointViewController *_Controller = [[SBCheckPointViewController alloc]initWithNibName:@"SBCheckPoints" bundle:nil];
    [self.navigationController pushViewController:_Controller animated:YES];
    NSMutableArray *arr = [[mDirections checkPoint] mPlaceTitle];
    _Controller.mCheckPoints = arr ;


}



//
-(void)removeRouteAnnotations
{
    NSMutableArray *mTempAnnotation;// = [mAnnotations retain];
    for (int idx = 0; idx < [mTempAnnotation count]; idx++) {
        [mMap.mapView removeAnnotations:[mTempAnnotation objectAtIndex:idx] ];
    }   
    mLoadBtn.title = @"ON";
    mLoadBtn.target = self;
    mLoadBtn.action = @selector(loadRouteAnnotations);
}


#pragma mark <UICGDirectionsDelegate> Methods

- (void)directionsDidFinishInitialize:(UICGDirections *)directions {
    [self updateRoute];
}

- (void)directions:(UICGDirections *)directions didFailInitializeWithError:(NSError *)error {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Map Directions" message:[error localizedFailureReason] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alertView show];
}

- (void)directionsDidUpdateDirections:(UICGDirections *)indirections {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

    UICGPolyline *polyline = [indirections polyline];
    NSArray *routePoints = [polyline routePoints];

    [mMap loadRoutes:routePoints]; // Loads route by getting the array of all coordinates in the route.

    UIToolbar *tools = [[UIToolbar alloc]
                        initWithFrame:CGRectMake(0.0f, 0.0f, 103.0f, 44.01f)]; // 44.01 shifts it up 1px for some reason
    tools.clearsContextBeforeDrawing = NO;
    tools.clipsToBounds = NO;
    tools.tintColor = [UIColor colorWithWhite:0.305f alpha:0.0f]; // closest I could get by eye to black, translucent style.
    // anyone know how to get it perfect?
    tools.barStyle = -1; // clear background
    NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:2];

    // Create a standard Load button.

    self.loadBtn = [[UIBarButtonItem alloc]initWithTitle:@"ON" 
                                                   style:UIBarButtonItemStyleBordered 
                                                  target:self 
                                                  action:@selector(loadRouteAnnotations)];

    [buttons addObject:mLoadBtn];

    // Add Go button.
    UIBarButtonItem *mGoBtn = [[UIBarButtonItem alloc] initWithTitle:@"Go" 
                                                               style:UIBarButtonItemStyleBordered 
                                                              target:self 
                                                              action:@selector(showCheckpoints)];
    [buttons addObject:mGoBtn];

    // Add buttons to toolbar and toolbar to nav bar.
    [tools setItems:buttons animated:NO];
    UIBarButtonItem *twoButtons = [[UIBarButtonItem alloc] initWithCustomView:tools];
    self.navigationItem.rightBarButtonItem = twoButtons;

    //Add annotations of different colors based on initial and final places.
    SBRouteAnnotation *startAnnotation = [[SBRouteAnnotation alloc] initWithCoordinate:[[routePoints objectAtIndex:0] coordinate]
                                                                                  title:mStartPoint
                                                                         annotationType:SBRouteAnnotationTypeStart];
    SBRouteAnnotation *endAnnotation = [[SBRouteAnnotation alloc] initWithCoordinate:[[routePoints lastObject] coordinate]
                                                                                title:mEndPoint
                                                                       annotationType:SBRouteAnnotationTypeEnd];


    [mMap.mapView addAnnotations:[NSArray arrayWithObjects:startAnnotation, endAnnotation,nil]];
}

- (void)directions:(UICGDirections *)directions didFailWithMessage:(NSString *)message {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Map Directions" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alertView show];
}

#pragma mark -

@end

Я пытался поместить свой код в новый проект (пустое приложение), и он работал нормально, я не понимал эту ошибку и ее возможные причины.

РЕДАКТИРОВАТЬ:

Я пытался отследить проблему путем устранения, и мой код работал нормально, когда я удаляю этот метод:

//Invoked when the class is instantiated in XIB

-(id)initWithCoder:(NSCoder*)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if( self)
    {
        [self customInitialization];
    }
    return self;
}

Однако при запуске мое приложение не отображаетсямне маршрут между двумя точками (цель приложения).Так что этот метод кажется важным для всего класса, потому что без него я не смог бы найти маршрут, а с другой стороны, когда он там, приложение зависало.Как мне справиться с этим противоречием?

1 Ответ

2 голосов
/ 11 января 2012

@ Винс выводит вас на правильный путь.Поскольку проблема заключается в том, что метод NSURL вызывается фреймворком (в данном случае Google Maps), вам необходимо отладить то, что вы передаете фреймворку.У вас также есть источник для фреймворка?Вы можете установить точки останова в loadWithStartPoint:endPoint:options:], чтобы увидеть, что происходит.

Одна вещь, которую я заметил, это то, что вы передаете NSMutableArray в качестве параметра endPoint, когда я считаю, что он ожидает NSString.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...