我试图找到使用NSTimer函数定期插入数组的10个信号强度值的平均值。我知道计时器正在运行,因为控制台日志,但10个值的数组没有。代码中是否存在小错误,或者if / else语句可能存在问题?
- (IBAction)getSignalAvg:(id)sender {
myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(arrayBuild)
userInfo:nil
repeats:YES];
}
- (void)arrayBuild {
loopCount++;
// Initialise Array
NSMutableArray *resultsArray = [[NSMutableArray alloc]init];
if (loopCount >= 11) {
// Invalidate Timer
[myTimer invalidate];
myTimer = nil;
// Find Average
NSNumber *avg = [resultsArray valueForKeyPath:@"@avg.self"];
// Change Text of Label to Average & Log
self.avgSignal.text = [NSString stringWithFormat:@"%@",avg];
NSLog(@"%@",avg);
}else{
// Declare Signal Strength
float signalstrength = CTGetSignalStrength();
// Individual Result & Convert to Integer
NSString *result = [NSString stringWithFormat:@"%f", signalstrength];
NSInteger resultInt = [result integerValue];
// Add Object
[resultsArray addObject:[NSNumber numberWithFloat:resultInt]];
// Change Text of Label Each Second
self.avgSignal.text = [NSString stringWithFormat:@"%d",loopCount];
NSLog(@"%f",signalstrength);
}
}
答案 0 :(得分:2)
每次调用arrayBuild
方法时,您都会创建一个新的NSMutableArray
,因此您只有一个值。
您需要为NSMutableArray
resultsArray
创建一个类实例。只需在此类的.h
文件中声明一个属性,如:
@property (nonatomic, strong) NSMutableArray *resultsArray;
在班级的init
中:
- (instancetype)init{
self = [super init];
if (self) {
_resultsArray = [[NSMutableArray alloc]init];
}
return self;
}
然后移除NSMutableArray *resultsArray = [[NSMutableArray alloc]init];
中的arrayBuild
并使用self.resultsArray
的{{1}}个身份。
答案 1 :(得分:1)
在.h文件中声明你是resultArray,因为每次你创建新数组时都是n。这就是为什么你无法做到这一点的原因。所以请像这样使用
.h文件
NSMutableArray *resultsArray;
.m文件
- (IBAction)getSignalAvg:(id)sender {
myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(arrayBuild)
userInfo:nil repeats:YES];
// Initialise Array
if([resultArray count] == 0)
resultsArray = [[NSMutableArray alloc]init];
else
[resultArray removeAllObjects];
}
- (void)arrayBuild {
loopCount++;
if (loopCount >= 11) {
// Invalidate Timer
[myTimer invalidate];
myTimer = nil;
// Find Average
NSNumber *avg = [resultsArray valueForKeyPath:@"@avg.self"];
// Change Text of Label to Average & Log
self.avgSignal.text = [NSString stringWithFormat:@"%@",avg];
NSLog(@"%@",avg);
}else{
// Declare Signal Strength
float signalstrength = CTGetSignalStrength();
// Individual Result & Convert to Integer
NSString *result = [NSString stringWithFormat:@"%f", signalstrength];
NSInteger resultInt = [result integerValue];
// Add Object
[resultsArray addObject:[NSNumber numberWithFloat:resultInt]];
// Change Text of Label Each Second
self.avgSignal.text = [NSString stringWithFormat:@"%d",loopCount];
NSLog(@"%f",signalstrength);
}
}