您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Debug 筆記:Xcode 5 下地圖代理不觸發,元凶竟是 ARC

編輯:iOS 開發綜合

症狀:一模一樣的程式碼,換個專案就不動了

某次專案要用到定位與地圖,我把先前寫好的 demo 直接搬了出來。奇怪的是,舊 demo 跑起來完全正常,但只要在 Xcode 5 底下新增一個專案、把程式碼貼進去,CLLocationManagerDelegate 的代理方法就完全不執行。

更麻煩的是 console 還被大量這類訊息洗版:

Error: CGBitmapContextCreate: unsupported parameter combination:
5 integer bits/component; 16 bits/pixel; 3-component color space;
kCGImageAlphaNoneSkipLast; 512 bytes/row.

vImage decode failed, falling back to CG path.

我把程式碼逐行比對了十幾次,確認與舊專案一字不差;上網翻了很多資料,也沒有找到對症的答案。

線索:差別不在程式碼,而在專案設定

既然程式碼相同、行為不同,問題就一定出在專案層級的設定。舊 demo 產於 Xcode 4.6 時代,當時 ARC 尚未是預設選項;而 Xcode 5 建立的新專案預設開啟 ARC。差異就在這裡。

解法:把 ARC 關掉

將 target 的 Automatic Reference Counting 設為 NO,重新編譯執行後,代理方法立刻正常回呼,地圖也順利定位並縮放到當前座標。

之所以會這樣,是因為舊程式碼裡混雜了 MRC 風格的寫法(例如 autorelease、缺乏 weak 參考的 delegate 宣告)。在 ARC 下,物件生命週期由編譯器接管,CLLocationManager 這種必須被強引用的物件,一旦沒有正確持有關係,就可能在你還沒收到回呼之前就被釋放掉,表現出來就是「代理方法永遠不執行」。

完整可跑的程序碼

環境:Xcode 5.0,Single View Application,導入 MapKit 與 CoreLocation,並將 ARC 設為 NO。

ViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController : UIViewController <CLLocationManagerDelegate>
{
    MKMapView *_mapView;
    UILabel *_showLabel;
}
@end

ViewController.m

#import "ViewController.h"
#import "MapAddress.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    CLLocationManager *manager = [[CLLocationManager alloc] init];
    manager.desiredAccuracy = kCLLocationAccuracyBest; // 定位精確度
    manager.distanceFilter = 1;                        // 更新距離門檻
    manager.delegate = self;
    [manager startUpdatingLocation];

    _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    _mapView.showsUserLocation = YES;
    [self.view addSubview:_mapView];
}

// 定位成功
- (void)locationManager:(CLLocationManager *)manager
    didUpdateLocations:(NSArray *)locations
{
    CLLocation *newLocation = [locations lastObject];
    NSString *str = [MapAddress getGoogleAddress:newLocation];
    NSLog(@"%@", str);

    CLLocationCoordinate2D coordinate = newLocation.coordinate;
    MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1);
    MKCoordinateRegion region = MKCoordinateRegionMake(coordinate, span);
    [_mapView setRegion:region animated:YES];
}

// 定位失敗
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    NSLog(@"定位失敗");
}

@end

MapAddress.h

#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@interface MapAddress : NSObject
+ (NSString *) getBaiduAddress:(CLLocation *)location;
+ (NSString *) getGoogleAddress:(CLLocation *)location;
@end

MapAddress.m

#import "MapAddress.h"

@implementation MapAddress

+ (NSString *) getBaiduAddress:(CLLocation *)location
{
    double latitude  = location.coordinate.latitude;
    double longtitude = location.coordinate.longitude;
    NSString *urlstr = [NSString stringWithFormat:
        @"https://api.map.baidu.com/geocoder?output=json&location=%f,%f&key=xxxxxxxx",
        latitude, longtitude];
    NSURL *url = [NSURL URLWithString:urlstr];
    return [NSString stringWithContentsOfURL:url
                                   encoding:NSUTF8StringEncoding
                                      error:nil];
}

+ (NSString *) getGoogleAddress:(CLLocation *)location
{
    NSString *urlstr = [NSString stringWithFormat:
        @"https://maps.google.com/maps/api/geocode/json?latlng=%f,%f&language=zh-CN&sensor=false",
        location.coordinate.latitude,
        location.coordinate.longitude];
    NSLog(@"%@", urlstr);
    NSURL *url = [NSURL URLWithString:urlstr];
    return [NSString stringWithContentsOfURL:url
                                   encoding:NSUTF8StringEncoding
                                      error:nil];
}

@end

這次經驗的三個 takeaway

  1. 行為不一致時,先懷疑環境而不是程式碼。逐字比對程式碼只會浪費時間。
  2. 舊專案搬新專案,務必檢查 ARC、Deployment Target、Build Settings。這三者是最常見的差異來源。
  3. 更根本的解法是改寫而非關閉 ARC。把 CLLocationManager 宣告為 delegate 的強屬性並正確持有,才是長久之計;關掉 ARC 只是讓舊寫法能跑的權宜之計。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved