當我將對象分配給實例變量時,存在某種保留問題。我的理解是所有的本地實例變量都是strong
,所以僅僅賦值就足以確保對象不會被銷燬,只要它被實例變量引用,但事實並非如此。當分配給它的實例變量時,對象似乎不會被保留
在下面的代碼中,我將實例MKRoute
變量myRoute
指定爲計算方向調用的路由。此時myRoute
存在並且有效,包含步驟和折線等。但後來在我的代碼中,我試圖訪問myRoute
,並且我得到了一個不良訪問。
它似乎仍然有一個內存指針值,但對象的其餘部分至少在調試器中消失了。沒有折線或步驟等,或者至少不是它應該是。我的代碼中沒有其他任務或修改或myRoute
。我需要做些什麼來確保這個對象不被破壞?
@implementation SomeClass
MKRoute *myRoute = nil;
.
.
.
-(void) showRoute:(MKMapItem *)origin destination:(MKMapItem*)destination
{
MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
request.source = origin;
request.destination = destination;
request.requestsAlternateRoutes = NO;
MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
[directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
if (error) {
NSLog(@"ERROR %@",error);
// Handle Error
} else {
[self drawRoute:response];
}
}];
}
-(void)drawRoute:(MKDirectionsResponse *)response
{
for (MKRoute *route in response.routes)
{
myRoute = route; // set the global route
[mapView addOverlay:route.polyline level:MKOverlayLevelAboveRoads];
}
}
.
.
.
@end
我很高興地承認它是一個全局變量VS實例變量,但我還是不明白爲什麼它失去了保留,如果我嘗試靜態或__strong上它仍然纏在賦值的變量聲明拖曳路線,後來走了。
僅供參考 - 如果myRoute被聲明在不中途的地方,那麼'myRoute'不是一個實例變量。 – rmaddy
您的編輯確認'myRoute'不是伊娃。這是一個文件全局變量。 – rmaddy