0

我正在制作一个应用程序来确定用户的位置并[locationManager startUpdatingLocation]initWithNibName函数中进行调用,但initWithNibName没有立即被调用,所以我在以下位置添加了对它的调用AppDelegate.m

WhereamiViewController *wvc = [[WhereamiViewController alloc] initWithNibName:@"WhereamiViewController" bundle:nil];

这可行,但是在函数中调用此函数会出现问题initWithNibName[locationManager startUpdatingLocation]. 它实际上什么也不返回。但是,如果我将代码更改为initWithNibName在我的viewDidLoad行中调用,它就可以工作。为什么是这样?我很困惑,一直在寻找答案,但我处于停滞状态。我知道需要调用 initWithNibName ,但我不明白为什么如果我从AppDelegate.m.

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations`

- (void)locationManager:(CLLocationManager *)manager
    didFailWithError:(NSError *)error

这是我的 initWithNibName 函数:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {
        locationManager = [[CLLocationManager alloc] init];

        locationManager.delegate = self;
        locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;

        // Set a movement threshold for new events.
        locationManager.distanceFilter = 500; // meters

        [locationManager startUpdatingLocation];
    }

    return self;
}
4

1 回答 1

0

您确实设置了 Xib 文件吗?要尝试的事情:如果您不使用 Nibs,则创建一个名为 init 的方法:

- (id) init {
self = [super init];
if(self) {
    //call code here
}
return self;
}

然后在应用程序委托中调用 nib 方法而不是调用 init

或者第二种选择是直接在 viewdidload 中调用代码,而不是在上面做

于 2013-11-03T02:23:55.627 回答