【发布时间】:2013-10-19 13:13:51
【问题描述】:
当我的应用程序在我的自定义注释方法中开始崩溃时,我了解到我的内存存在问题。我确信管理地图的视图控制器 100% 应该已经从视图堆栈中弹出。
这里是注解的代码,TaxiArrivingAnnotation.h:
#import <Foundation/Foundation.h>
@import MapKit;
@interface TaxiArrivingAnnotation : NSObject<MKAnnotation>
@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic) int minutesToTaxiArrival;
-(void) startTimer;
@end
#import "TaxiArrivingAnnotation.h"
#define SECONDS_IN_A_MINUTE 60
@interface TaxiArrivingAnnotation ()
@property (nonatomic) NSTimer * timer;
@property (nonatomic) NSDate * timeOfArrival;
@property (nonatomic, weak) id token1;
@property (nonatomic, weak) id token2;
@end
@implementation TaxiArrivingAnnotation
- (id)init
{
self = [super init];
if (self) {
__weak TaxiArrivingAnnotation * this = self;
self.token1 = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification object:nil queue:nil usingBlock:^(NSNotification *note)
{
NSLog(@"DID BECOME ACTIVE");
NSTimeInterval secondsLeft = [this.timeOfArrival timeIntervalSinceNow];
if (secondsLeft < 0) {
self.minutesToTaxiArrival = 0;
return;
}
this.minutesToTaxiArrival = secondsLeft / SECONDS_IN_A_MINUTE;
[this startTimer];
}];
self.token2 = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillResignActiveNotification object:nil queue:nil usingBlock:^(NSNotification *note)
{
NSLog(@"WILL RESIGN ACTIVE");
[this.timer invalidate];
this.timer = nil;
}];
}
return self;
}
-(void) setMinutesToTaxiArrival:(int)newMinutes {
self->_minutesToTaxiArrival = newMinutes;
self->_timeOfArrival = [NSDate dateWithTimeIntervalSinceNow:SECONDS_IN_A_MINUTE * newMinutes];
if (newMinutes < 0) {
[self.timer invalidate];
}
}
-(void) startTimer {
self.timer = [NSTimer timerWithTimeInterval:SECONDS_IN_A_MINUTE target:self selector:@selector(aMinutedPassed) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}
-(void) aMinutedPassed {
self.minutesToTaxiArrival--;
}
-(void) dealloc {
NSLog(@"DEALLOC");
if (self.timer != nil && [self.timer isValid])
[self.timer invalidate];
[[NSNotificationCenter defaultCenter] removeObserver:self.token1];
[[NSNotificationCenter defaultCenter] removeObserver:self.token2];
}
@end
我在viewDidAppear 上添加注释并在viewDidDisappear 上删除它。不仅删除它,而且nil-ing 引用。管理视图控制器dealloc被调用时,dealloc方法仍然没有被调用。
真正的问题是,由于注释已被释放,计时器和通知会触发并且应用程序崩溃。
【问题讨论】:
标签: ios map automatic-ref-counting mapkit mkannotation