gpt4 book ai didi

iphone - 如何释放具有 NStimer 工作的对象

转载 作者:太空狗 更新时间:2023-10-30 04:01:28 25 4
gpt4 key购买 nike

我不想在 [myview 发布] 之前编写类似“myview.timer invalidate”的代码。但是如果计时器在工作,我就不能释放我的 View ,因为计时器保留了我的 View 。我该怎么办?

我想让“myview”类变得简单,只需调用 [myview init] 和 [myview release]

myview.h

@interface MyView : UIView {
NSString *str;
NSTimer *timer;
}
@property(nonatomic, retain) NSString *str;
@property(nonatomic, assign) NSTimer *timer;
- (void)start;
- (void)doAction;
@end

myview.m

@implementation MyView
@synthesize str, timer;
- (id)initWithFrame:(CGRect)frame {

self = [super initWithFrame:frame];
if (self) {
// Initialization code.
NSString *_str = [[NSString alloc] initWithFormat:@"Timer is Running!!! Not Release"];
self.str = _str;
[_str release];
}
return self;
}

- (void)start {
NSTimer *_timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(doAction) userInfo:nil repeats:YES];
self.timer = _timer;
}

- (void)doAction {
NSLog(@"%@",self.str);
}


- (void)dealloc {
[str release];
[timer invalidate];
timer = nil;
[super dealloc];
}

contrllor.m

- (void)viewDidLoad {
MyView *my_view = [[MyView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
self.myView = my_view;
[my_view release];

[myView start];
[self.view addSubview:myView];

[super viewDidLoad];
}

- (IBAction)releaseMyView {
[myView removeFromSuperview];
[myView release];
}

最佳答案

重复计时器保留其目标。所以如果你使用重复定时器那么你必须使它失效,并且失效的地方一定不能是deallocdealloc 不会被调用,除非你使计时器无效。这就是 NSTimer 的设计方式。由于您有一个 start 方法,如果您正在寻找更具可读性的代码,您可以编写一个使计时器无效的 stop 方法。逻辑很简单:如果你已经开始,你就需要停下来。

另一个选项是您可以使用不同的对象作为计时器的目标,而不是 self。然后你可以在 dealloc 中使定时器无效。但这可能不值得付出努力。

关于iphone - 如何释放具有 NStimer 工作的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6203285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com