【问题标题】:MKMapView must be initialized on the main threadMKMapView 必须在主线程上初始化
【发布时间】:2012-01-10 14:20:22
【问题描述】:

我是 iphone 新手,使用 MKMapView 在我的应用程序中加载谷歌地图。但它抛出异常“MKMapView 必须在主线程上初始化。”。那么我应该在哪里初始化我的MKMapView 对象。我正在viewDidLoad() 中初始化。

提前致谢.....

【问题讨论】:

  • 你真的应该提供更多细节......

标签: ios cocoa-touch mkmapview


【解决方案1】:

它没有在主线程上创建的原因是 2 个选项之一

  1. 创建它的视图位于后台线程之一
  2. 您正在调用 performSelectorInBackground: 来创建您的视图

在主线程调用performSelectorOnMainThread:执行一个函数

题外话:如果函数需要超过 1 个参数,请将其更改为 NSDictionary 并将所有设置加载到 Dictionary 中并将其传递给 eg

NSDictionary *params = ...... //load your parameters into here

[myMapView performSelectorOnMainThread:@selector(initMap:)
                                withObject:params
                             waitUntilDone:YES];

另请阅读以下FirstSecond 以更好地了解iOS 中的多线程

【讨论】:

  • 我在 viewDidLoad 中使用以下代码,这个视图被另一个视图调用 mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0,0,780,920)]; mapView.delegate=自己; [self.view addSubview:mapView]; [NSThread detachNewThreadSelector:@selector(displayMyMap) toTarget:self withObject:nil];
  • 您正在创建一个新线程,请尝试更改为 performSelectorOnMainThread 而不是 detachNewThreadSelector
  • 感谢您的建议,但我仍然面临同样的问题
【解决方案2】:

使用 Swift 3,以下将确保您的函数在主线程上运行。 OperationQueue.main.addOperation{"你的 segue 或函数调用"}

【讨论】:

  • 欢迎来到 SO。请用反引号包裹您的代码,以便它显示为代码。
【解决方案3】:

我收到了这个错误:

MKMapView 必须在主线程初始化

当我尝试以这种方式更改自定义UITableViewCell 的内容时:

[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:@[myIndexPath] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];

The UITableviewCell in the corresponding indexpath contained a MKMapView that I tried to change its region.

myTabelViewCell *cell = [self.tableView cellForRowAtIndexPath:myIndexPath];
[cell setContentWithLatitude:currentLatitude longitude:currentLongitude];

使用上面的代码而不是[self.tableView reloadData] 只刷新一个单元格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 2017-07-30
    相关资源
    最近更新 更多