gpt4 book ai didi

使用 NSTimer 通过单元测试后,iOS 逻辑单元测试目标崩溃

转载 作者:行者123 更新时间:2023-11-28 20:40:43 26 4
gpt4 key购买 nike

我想要一个计时器类,它可以在还剩 1/2/3 秒时向委托(delegate)人发送消息。

我的测试目标一直崩溃。

  • iOS 逻辑单元测试目标。
  • 测试使用重复 NSTimer 计时持续时间的类
  • 一个没有断言的测试。测试通过,但随后目标崩溃:

/Developer/Tools/RunPlatformUnitTests.include:第 415 行:770 总线错误“${THIN_TEST_RIG}”“${OTHER_TEST_FLAGS}”“${TEST_BUNDLE_PATH}”

在我看来,这是某种内存分配错误,但我不知道我遗漏了什么。该问题以某种方式与停止计时器例程有关。只有当计时器用完时,目标才会崩溃。

我尝试过的事情

  • 构建和分析 - 未报告错误
  • 从链接器标志中删除 -framework 和 UIKit
  • 删除 dealloc - 这没有效果

测试代码

-(void)testGivenThreeSecondDurationAtOneSecondDelegateShouldBeToldToShowGreenCard {
JGTimerController *timer = [JGTimerController timerWithDurationValue:1 delegate:nil];
[timer startTimer];

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.1]];
}

类代码

@interface JGTimerController : NSObject {
NSNumber *duration;
NSTimer *timer;
id <NSObject, JGTimerControllerDelegate> _delegate;
}
@property (nonatomic, retain) NSNumber *duration;
... public methods...
@end


@implementation JGTimerController

@synthesize duration;

+(JGTimerController *)timerWithDurationValue:(NSUInteger)durationValue delegate:(id <JGTimerControllerDelegate>)delegate_ {
JGTimerController *instance = [[[JGTimerController alloc] initWithDurationValue:durationValue delegate:delegate_] autorelease];
return instance;
}

-(JGTimerController *)initWithDurationValue:(NSUInteger)durationValue delegate:(id <JGTimerControllerDelegate>)delegate_ {
self = [super init];
timer = nil;
[self setDurationValue:durationValue];
_delegate = delegate_;
return self;
}

-(NSUInteger)durationValue {
NSNumber *result = [self duration];
return result ? [result intValue] : 0;
}

-(void)setDurationValue:(NSUInteger)value_ {
[self setDuration:[NSNumber numberWithInt:value_]];
}

-(BOOL)stopTimerAtZeroDuration:(NSTimer *)timer_ {
if ([self durationValue] == 0) {
[self stopTimer];
return YES;
}
return NO;
}

-(void)startTimer {
if ([self stopTimerAtZeroDuration:nil])
return;

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerDidCountDownByASecond:) userInfo:nil repeats:YES];
}

-(void)stopTimer {
if ([self durationValue] == 0 && [_delegate conformsToProtocol:@protocol(JGTimerControllerDelegate)])
[_delegate showRedCard];

[timer invalidate];
[timer release];
}

-(BOOL)timerIsRunning {
return (timer != nil);
}

-(void)timerDidCountDownByASecond:(NSTimer *)timer_ {
[self setDurationValue:[self durationValue] - 1];
[self stopTimerAtZeroDuration:timer_];
}

-(void)dealloc {
[_delegate release];
[timer release];
[duration release];
[super dealloc];
}

@end

最佳答案

dealloc 中不应该有 [_delegate release] 因为你没有保留它。

关于使用 NSTimer 通过单元测试后,iOS 逻辑单元测试目标崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8685889/

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