2012-05-25 41 views
0

對不起,它的一個基本問題,我想知道爲什麼我的代碼不需要mapView的alloc/init。它會在保留時自動發生嗎?我沒有使用ARC和我的MKMapView * mapView的alloc/init它不會導致錯誤,但地圖視圖不顯示位置信息,也不會顯示爲混合類型....但在移除alloc/init的聲明來viewDidLoad它的作品都很好!爲什麼?初始化和分配無弧?

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

@interface MDViewController : UIViewController<CLLocationManagerDelegate, MKMapViewDelegate> 

@property (retain, nonatomic) IBOutlet MKMapView* mapView; 

@end 


----- 

#import "MDViewController.h" 

@interface MDViewController() 
{ 
    CLLocationManager* lmanager; 
} 

@end 

@implementation MDViewController 

@synthesize mapView; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    lmanager= [[CLLocationManager alloc]init]; 
    lmanager.delegate=self; 
    lmanager.desiredAccuracy=kCLLocationAccuracyBest; 
    lmanager.distanceFilter=kCLDistanceFilterNone; 
    [lmanager startUpdatingLocation]; 
    //mapView = [[MKMapView alloc]init];//without allocating here it works 
    mapView.delegate=self; 
    mapView.mapType=MKMapTypeHybrid; 
} 

-(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
     //update map 
    MKCoordinateSpan span; 
    span.latitudeDelta= .001; 
    span.longitudeDelta=.001; 


    MKCoordinateRegion region; 
    region.center= newLocation.coordinate; 
    region.span=span; 
    [mapView setRegion:region animated:YES]; 
    [mapView setShowsUserLocation:YES]; 

} 

回答

1

您不需要爲init map分配init,因爲它是由Xib完成的。當加載接口xib時,框架看到你有一個凍結的mapview並自動分配init,然後將該mapview分配給viewcontroller代碼中的那個。 如果在你的代碼中你分配了初始值,你就會中斷兩者之間的連接。

使其工作的一種方法是在你的IB xib中沒有mapview,並分配它init,setDelegate,設置框架,最後添加它的視圖作爲主視圖的子視圖。

我儘量保持簡潔。我希望我們對你很清楚。 ARC並沒有任何關係。

+0

非常感謝您的明確解釋。它清除了我的困惑。 – sani