ios - How can I find the average of 10 values in an array in Objective-C -
i attempting find average of 10 signal strength values have been inserted array periodically nstimer function. know timer working due console logs, array of 10 values not. there small error in code or potentially issue if/else statement?
- (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 average & log self.avgsignal.text = [nsstring stringwithformat:@"%@",avg]; nslog(@"%@",avg); }else{ // declare signal strength float signalstrength = ctgetsignalstrength(); // individual result & convert 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); } }
declare yout resultarray in .h file because each n every time you're creating new array. that's why you're not able that. please use this
.h file
nsmutablearray *resultsarray;
.m file
- (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 average & log self.avgsignal.text = [nsstring stringwithformat:@"%@",avg]; nslog(@"%@",avg); }else{ // declare signal strength float signalstrength = ctgetsignalstrength(); // individual result & convert 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); } }
Comments
Post a Comment