开发者

Objective-C for Dummies: How to make App Delegate communicate with Controllers?

how can I invoke methods in my controllers from within the app delegate. For example, my application uses the app delegate to monitor the user's location. After the location has been determined I want to call a method on a controller which has a MKMapView on it and show the user's location on it. How can I go about doing that?

Here's my current code:

//  AppDelegate.m
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [[[DashboardViewController alloc] initWithNibName:@"DashboardViewController" bundle:nil] displayMyLocation:newLocation.coordinate];
}

Also tried this, which is crashing with SIGABRT, but is at least attempting to call the method:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [(DashboardViewController *)dashboardViewController displayMyLocation:manager];
}

Alternatively, now that I think about it, would it be wrong to have the controller also monitor the user's location and just self invoke it's methods? If I remember correctly having multiple CLLocationManagerDelegate delegates didn't affect performance because they all access the GPS identically? Is that right or wrong? It just kinda seems dumb to have multiple instances of the same thing...

Thanks in advance!

UPDATE for @neva开发者_Python百科n

The map code:

- (void)displayMyLocation:(CLLocation *)location {
    MKCoordinateSpan span;
    MKCoordinateRegion region;

    span.latitudeDelta = 0.02;
    span.longitudeDelta = 0.02;

    region.center = location.coordinate;
    region.span = span;

    [map setRegion:region];
}


It would certainly be a good idea to have your controller monitoring for location events.

A fairly decent alternative would be to use the notification center to notify the controller that a new location is available. I actually did exactly that in one of my applications. Check out line 70 of this file to see how to send a notification and line 54 of this file to see how tp subscribe tp these notifications.


locationManager:didUpdateToLocation is called many times, each time the device gets a new fix on the location, so you'll end up allocing and initing your DashboardViewController many times. The proper way to do this would be to alloc and init a dashboardViewController instance variable when you set up your app delegate, then use that instance variable. It looks like you've done that in your second piece of code, but I don't understand why you have to cast it to be a DashboardViewController.

It would be better again to put the location manager into the same place as your mapview. Why not move locationManager:didUpdateToLocation to there?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜