ios - 如何在 Objective-C 中的数组中找到 10 个值的平均值

标签 ios objective-c arrays

我试图找到使用 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);

    }
}

最佳答案

每次调用 arrayBuild 方法时,您都会创建一个新的 NSMutableArray,因此其中只有一个值。

您需要为 NSMutableArray resultsArray 创建一个类实例。只需在此类的 .h 文件中声明一个属性,例如:

@property (nonatomic, strong) NSMutableArray *resultsArray;

在类的 init 中:

- (instancetype)init{
    self = [super init];

    if (self) {
        _resultsArray = [[NSMutableArray alloc]init];
    }

    return self;
}

并在 arrayBuild 中删除 NSMutableArray *resultsArray = [[NSMutableArray alloc]init]; 并使用 self.resultsArray instate of 结果数组

关于ios - 如何在 Objective-C 中的数组中找到 10 个值的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25360828/

相关文章:

iphone - 在 iPhone 上存储信息

iphone - 如何实现initWithObjects?

java - 选择排序返回不在我的数组中的零

javascript - JS : find lowest/highest number from array within a specific range

javascript - Angular : how can I order ng-repeat by array order?

ios - 如何在不等待 App Review 的情况下继续使用 TestFlight 功能

iphone - 您是否必须将 Sprite 表与 CCSpriteFrameCache 一起使用?

ios - 客户端-服务器数据同步算法

ios - 如何在 Xcode Playground 中实现自定义字体

objective-c - 将对象添加到 NSMutableArray 属性