Changing labels after swithiching between views - iphone

I have two-views app for iPhone. On first one I call code that does this every second with NSTimer:
update variables
make sound
update label
update image position
When I start app - everything works perfect. When I go to other view and then go back to first screen - 1 and 2 works fine, but 3 and 4 resets and does not work at all.
What could be the problem?
Looks like it loses "hooks" to elements...
-(void)countup {
DeccelFloat += 0.4;
SpeedFloat += 5/(DeccelFloat);
SpeedInt = lroundf(SpeedFloat);
speed.text = [NSString stringWithFormat:#"%i", SpeedInt];
imageview.center = CGPointMake(imageview.center.x, imageview.center.y+3);
if (imageview.center.y < 280) {
imageview.alpha = 1;
if (SpeedFloat > MaxSpeedValue) {
[self playalarm];
}else{
[self playbeep];
}
}
if ((imageview.center.y >= 280) && (imageview.center.y < 283)) {
if (SpeedFloat > MaxSpeedValue) {
[self playshot];
}else{
[self playbeepbeep];
}
}
if ((imageview.center.y >= 280) && (imageview.center.y < 350)) {
imageview.alpha = 0.5-(0.5/70)*(imageview.center.y - 280);
}
if (imageview.center.y >= 350) {
imageview.alpha = 0;
imageview.center = CGPointMake(imageview.center.x, 180);
}
}
And here is my timer:
- (void)viewDidLoad
{
[super viewDidLoad];
MaxSpeedValue = 60;
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSNumber *maxspeedsetttings = nil;
NSNumber *blinkingsetttings = nil;
NSNumber *startedsetttings = nil;
if (standardUserDefaults) {
maxspeedsetttings = [standardUserDefaults objectForKey:#"maxspeedsetttings"];
blinkingsetttings = [standardUserDefaults objectForKey:#"blinkingsetttings"];
startedsetttings = [standardUserDefaults objectForKey:#"startedsetttings"];
}
MaxSpeedDef = [maxspeedsetttings intValue];
if (MaxSpeedDef == 1) {
maxspeed.text = [NSString stringWithFormat:#"%i", MaxSpeedValue];
}else{
maxspeed.alpha = 0;
maxspeedlabel.alpha = 0;
}
imageview.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"0.png"],
[UIImage imageNamed:#"5.png"],
[UIImage imageNamed:#"10.png"],
nil];
imageview.animationDuration = 1;
imageview.animationRepeatCount = 0;
BlinkingDef = [blinkingsetttings intValue];
if (BlinkingDef == 1) {
[imageview startAnimating];
}else{
[imageview stopAnimating];
}
[self.view addSubview:imageview];
StartedDef = [startedsetttings intValue];
if (StartedDef == 0) {
SpeedFloat = 0;
DeccelFloat = 0;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(countup) userInfo:nil repeats:YES];
StartedDef = 1;
if (standardUserDefaults) {
[standardUserDefaults setObject:[NSNumber numberWithInt:StartedDef] forKey:#"startedsetttings"];
[standardUserDefaults synchronize];
}
}
}

Related

UIApplicationWillEnterForegroundNotification not called

Hi I am very new in Iphone Development. I have a question :
I am using UIApplicationDeligate in my Appdeligate class and in this class i use two methods
applicationDidEnterBackground and applicationdisEnterForeGround. then these method works fine , when my app goes in background or in comes in foreground then flow goes inside these method.
But in another UiViewController class i attach listener for UIApplicationdidEnterForegroundNotification and UiApplicationdidEnterBackgroundNotification.
now when my app goes in background then flow goes in background method but when my app comes in foreground then app flow never comes in foreground method.
code which i am using in AppDelegate Class :
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:timertimetobefired forKey:#"TimerTimeToFired"];
[defaults setValue:timerrecipename forKey:#"TimerRecipeName"];
[defaults setObject:storingbuttonstate forKey:#"TimerButtonState"];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
timertimetobefired = [defaults objectForKey:#"TimerTimeToFired"];
timerrecipename = [defaults objectForKey:#"TimerRecipeName"];
storingbuttonstate = [defaults objectForKey:#"TimerButtonState"];
}
and code which i am using inside UiViewController class :
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(goBackground)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:#"forground"
selector:#selector(doMyLayoutStuff:)
name: UIApplicationWillEnterForegroundNotification
object:nil];
- (void) goBackground
{
if(timer != nil && [timer isValid])
{
[timer invalidate], timer = nil;
}
}
can anyone tell me what wrong with this code . Thanks in advance.
code inside doMylayoutStuff :
- (void)doMyLayoutStuff:(id)sender
{
fortimer=0;
appdelegate.imgRecipePhoto=nil;
recipeMakingTime=0;
arrForStepsReminder=[[NSMutableArray alloc]init];
[arrForStepsReminder removeAllObjects];
arrForSteps5=[[NSMutableArray alloc]init];
[arrForSteps5 removeAllObjects];
arrForButtonSelection=[[NSMutableArray alloc]init];
[arrForButtonSelection removeAllObjects];
[arrForSteps5 addObjectsFromArray:appdelegate.arrStepsandTime];
arrayforshowingdata = [[NSMutableArray alloc]initWithCapacity:arrForSteps5.count];
for (int i=0; i<[arrForSteps5 count]; i++)
{
//nitin tyagi. 6/08/2013.
// NSString *str12=[[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipestepTime"];
// if (str12.length==0)
// {
// [arrForSteps5 removeObjectAtIndex:i];
// }
// else
// {
// }
NSString *timer1 = [[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipeTimer1"];
NSString *timer2 = [[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipeTimer2"];
NSString *timer3 = [[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipeTimer3"];
NSString *timer4 = [[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipeTimer4"];
timer1 = [timer1 stringByReplacingOccurrencesOfString:#" " withString:#""];
timer2 = [timer2 stringByReplacingOccurrencesOfString:#" " withString:#""];
timer3 = [timer3 stringByReplacingOccurrencesOfString:#" " withString:#""];
timer4 = [timer4 stringByReplacingOccurrencesOfString:#" " withString:#""];
NSMutableArray *finaltimerarray = [[NSMutableArray alloc]init];
int totalminute = 0;
int hours = 0;
if(([timer1 hasSuffix:#"mins"] || [timer1 hasSuffix:#"minute"] || [timer1 hasSuffix:#"min"]) || ([timer1 isEqualToString:#"0"]))
{
if(![timer1 isEqualToString:#"0"]){
NSRange range = [timer1 rangeOfString:#"min"];
NSString *minutes = [timer1 substringToIndex:range.location];
totalminute = totalminute + [minutes intValue];
NSNumber* xWrapped = [NSNumber numberWithInt:[minutes intValue]];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"totalminute minute is = %#",totalminute);
}
else if(([timer1 hasSuffix:#"hours"] || [timer1 hasSuffix:#"hrs"] || [timer1 hasSuffix:#"hour"] || [timer1 hasSuffix:#"hr"]) )
{
if(![timer1 isEqualToString:#"0"]){
NSRange range = [timer1 rangeOfString:#"h"];
NSString *hours = [timer1 substringToIndex:range.location];
int minute = [hours intValue] * 60;
totalminute = totalminute + minute;
NSNumber* xWrapped = [NSNumber numberWithInt:minute];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer1 minute is = %#",minutes);
}
if(([timer2 hasSuffix:#"mins"] || [timer2 hasSuffix:#"minute"] || [timer2 hasSuffix:#"min"]) || ([timer2 isEqualToString:#"0"]))
{
if(![timer2 isEqualToString:#"0"]){
NSRange range = [timer2 rangeOfString:#"min"];
NSString *minutes = [timer2 substringToIndex:range.location];
totalminute = totalminute + [minutes intValue];
NSNumber* xWrapped = [NSNumber numberWithInt:[minutes intValue]];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer2 minute is = %#",minutes);
}
else if(([timer2 hasSuffix:#"hours"] || [timer2 hasSuffix:#"hrs"] || [timer2 hasSuffix:#"hour"] || [timer2 hasSuffix:#"hr"]) )
{
if(![timer2 isEqualToString:#"0"])
{
NSRange range = [timer2 rangeOfString:#"h"];
NSString *hours = [timer2 substringToIndex:range.location];
int minute = [hours intValue] * 60;
totalminute = totalminute + minute;
NSNumber* xWrapped = [NSNumber numberWithInt:minute];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer1 minute is = %#",minutes);
}
if(([timer3 hasSuffix:#"mins"] || [timer3 hasSuffix:#"minute"] || [timer3 hasSuffix:#"min"]) || ([timer3 isEqualToString:#"0"]))
{
if( ![timer3 isEqualToString:#"0"])
{
NSRange range = [timer3 rangeOfString:#"min"];
NSString *minutes = [timer3 substringToIndex:range.location];
totalminute = totalminute + [minutes intValue];
NSNumber* xWrapped = [NSNumber numberWithInt:[minutes intValue]];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer3 minute is = %#",minutes);
}
else if(([timer3 hasSuffix:#"hours"] || [timer3 hasSuffix:#"hrs"] || [timer3 hasSuffix:#"hour"] || [timer3 hasSuffix:#"hr"]) )
{
if(![timer3 isEqualToString:#"0"]){
NSRange range = [timer3 rangeOfString:#"h"];
NSString *hours = [timer3 substringToIndex:range.location];
int minute = [hours intValue] * 60;
totalminute = totalminute + minute;
NSNumber* xWrapped = [NSNumber numberWithInt:minute];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer1 minute is = %#",minutes);
}
if(([timer4 hasSuffix:#"mins"] || [timer4 hasSuffix:#"minute"] || [timer4 hasSuffix:#"min"]) || ([timer4 isEqualToString:#"0"]))
{
if(![timer4 isEqualToString:#"0"])
{
NSRange range = [timer4 rangeOfString:#"min"];
NSString *minutes = [timer4 substringToIndex:range.location];
totalminute = totalminute + [minutes intValue];
NSNumber* xWrapped = [NSNumber numberWithInt:[minutes intValue]];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer4 minute is = %#",minutes);
}
else if(([timer4 hasSuffix:#"hours"] || [timer4 hasSuffix:#"hrs"] || [timer4 hasSuffix:#"hour"] || [timer4 hasSuffix:#"hr"]) )
{
if(![timer4 isEqualToString:#"0"]){
NSRange range = [timer4 rangeOfString:#"h"];
NSString *hours = [timer4 substringToIndex:range.location];
int minute = [hours intValue] * 60;
totalminute = totalminute + minute;
NSNumber* xWrapped = [NSNumber numberWithInt:minute];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer1 minute is = %#",minutes);
}
[arrayforshowingdata addObject:finaltimerarray];
[finaltimerarray release];
}
for (int i=0; i<[arrayforshowingdata count]; i++)
{
NSMutableArray *arraydata = [arrayforshowingdata objectAtIndex:i];
for (int j=0; j<[arraydata count]; j++)
{
[arrForStepsReminder addObject:#"0"];
}
[arrForButtonSelection addObject:#"M"];
}
lblDisplayTimer.text=#"00:00:00";
lblRecipeName.text=appdelegate.strRecipeName;
currentdate = [NSDate date];
NSDate *timetobefired = appdelegate.timertimetobefired;
timerrecipe = appdelegate.timerrecipename;
if(timerrecipe != nil && ([timerrecipe isEqualToString:appdelegate.strRecipeName]) && timetobefired != nil)
{
NSTimeInterval secondsBetween = [timetobefired timeIntervalSinceDate:currentdate];
NSInteger time = round(secondsBetween);
int second = (int)time;
if(second > 0)
{
secondsLeft = second;
arrForButtonSelection = appdelegate.storingbuttonstate;
[btnOnOff setOn:YES];
if(![timer isValid])
{
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateCountdown) userInfo:nil repeats:YES];
}
}
else
{
secondsLeft = 0;
}
}
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(goBackground)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(doMyLayoutStuff:)
name: UIApplicationWillEnterForegroundNotification
object:nil];
}
Change the observer to "self" in your addObserver call
i.e
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(doMyLayoutStuff:)
name: UIApplicationWillEnterForegroundNotification
object:nil];

Application is crashing in my iOS simulator when I try to draw second plot in core-plot graph

`
#import "TUTSimpleScatterPlot.h"
#import "CPDConstants.h"
#import "CPDStockPriceStore.h"
#implementation TUTSimpleScatterPlot
#synthesize hostView = _hostingView;
#synthesize graph = _graph;
#synthesize graphEmpActualWeightData = _graphEmpActualWeightData;
#synthesize graphEmpGoalWeightData = _graphEmpGoalWeightData;
// Initialise the scatter plot in the provided hosting view with the provided data.
// The data array should contain NSValue objects each representing a CGPoint.
-(id)initWithHostingView:(CPTGraphHostingView *)hostingView andEmpActualWeight:(NSMutableArray *)valuesEmpActualWeight andEmpGoalWeight:(NSMutableArray *)valuesEmpGoalWeight
{
self = [super init];
if ( self != nil ) {
self.hostView = hostingView;
self.graphEmpActualWeightData = valuesEmpActualWeight;
self.graphEmpGoalWeightData = valuesEmpGoalWeight;
self.graph = nil;
}
return self;
}
#pragma mark - Chart behavior
-(void)initPlot {
[self configureGraph];
[self configurePlots];
[self configureAxes];
}
-(void)configureGraph {
// 1 - Create the graph
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
[graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
self.hostView.hostedGraph = graph;
// 2 - Set graph title
NSString *title = #"Body weight actual and goal";
graph.title = title;
// 3 - Create and set text style
CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
titleStyle.color = [CPTColor whiteColor];
titleStyle.fontName = #"Helvetica-Bold";
titleStyle.fontSize = 16.0f;
graph.titleTextStyle = titleStyle;
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
graph.titleDisplacement = CGPointMake(0.0f, 10.0f);
// 4 - Set padding for plot area
[graph.plotAreaFrame setPaddingLeft:30.0f];
[graph.plotAreaFrame setPaddingBottom:30.0f];
// 5 - Enable user interactions for plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
}
-(void)configurePlots {
// 1 - Get graph and plot space
CPTGraph *graph = self.hostView.hostedGraph;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
// 2 - Create the two plots
CPTScatterPlot *actualPlot = [[CPTScatterPlot alloc] init];
actualPlot.dataSource = self;
actualPlot.identifier = CPDTickerSymbolActual;
CPTColor *actualColor = [CPTColor redColor];
[graph addPlot:actualPlot toPlotSpace:plotSpace];
CPTScatterPlot *goalPlot = [[CPTScatterPlot alloc] init];
goalPlot.dataSource = self;
goalPlot.identifier = CPDTickerSymbolGoal;
CPTColor *goalColor = [CPTColor greenColor];
[graph addPlot:goalPlot toPlotSpace:plotSpace];
// 3 - Set up plot space
[plotSpace scaleToFitPlots:[NSArray arrayWithObjects:actualPlot,nil]];
CPTMutablePlotRange *xRange = [plotSpace.xRange mutableCopy];
[xRange expandRangeByFactor:CPTDecimalFromCGFloat(1.1f)];
plotSpace.xRange = xRange;
CPTMutablePlotRange *yRange = [plotSpace.yRange mutableCopy];
[yRange expandRangeByFactor:CPTDecimalFromCGFloat(1.2f)];
plotSpace.yRange = yRange;
// 4 - Create styles and symbols
CPTMutableLineStyle *actualLineStyle = [actualPlot.dataLineStyle mutableCopy];
actualLineStyle.lineWidth = 2.5;
actualLineStyle.lineColor = actualColor;
actualPlot.dataLineStyle = actualLineStyle;
CPTMutableLineStyle *actualSymbolLineStyle = [CPTMutableLineStyle lineStyle];
actualSymbolLineStyle.lineColor = actualColor;
CPTPlotSymbol *actualSymbol = [CPTPlotSymbol hexagonPlotSymbol];
actualSymbol.fill = [CPTFill fillWithColor:actualColor];
actualSymbol.lineStyle = actualSymbolLineStyle;
actualSymbol.size = CGSizeMake(6.0f, 6.0f);
actualPlot.plotSymbol = actualSymbol;
CPTMutableLineStyle *goalLineStyle = [goalPlot.dataLineStyle mutableCopy];
goalLineStyle.lineWidth = 1.0;
goalLineStyle.lineColor = goalColor;
goalPlot.dataLineStyle = goalLineStyle;
CPTMutableLineStyle *goalSymbolLineStyle = [CPTMutableLineStyle lineStyle];
goalSymbolLineStyle.lineColor = goalColor;
CPTPlotSymbol *goalSymbol = [CPTPlotSymbol starPlotSymbol];
goalSymbol.fill = [CPTFill fillWithColor:goalColor];
goalSymbol.lineStyle = goalSymbolLineStyle;
goalSymbol.size = CGSizeMake(6.0f, 6.0f);
goalPlot.plotSymbol = goalSymbol;
}
-(void)configureAxes {
// 1 - Create styles
CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
axisTitleStyle.color = [CPTColor whiteColor];
axisTitleStyle.fontName = #"Helvetica-Bold";
axisTitleStyle.fontSize = 12.0f;
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 2.0f;
axisLineStyle.lineColor = [CPTColor whiteColor];
CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
axisTextStyle.color = [CPTColor whiteColor];
axisTextStyle.fontName = #"Helvetica-Bold";
axisTextStyle.fontSize = 11.0f;
CPTMutableLineStyle *tickLineStyle = [CPTMutableLineStyle lineStyle];
tickLineStyle.lineColor = [CPTColor whiteColor];
tickLineStyle.lineWidth = 2.0f;
CPTMutableLineStyle *gridLineStyle = [CPTMutableLineStyle lineStyle];
tickLineStyle.lineColor = [CPTColor blackColor];
tickLineStyle.lineWidth = 1.0f;
// 2 - Get axis set
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) self.hostView.hostedGraph.axisSet;
// 3 - Configure x-axis
CPTAxis *x = axisSet.xAxis;
x.title = #"Weeks ->";
x.titleTextStyle = axisTitleStyle;
x.titleOffset = 15.0f;
x.axisLineStyle = axisLineStyle;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.labelTextStyle = axisTextStyle;
x.majorTickLineStyle = axisLineStyle;
x.majorTickLength = 4.0f;
x.tickDirection = CPTSignNegative; //commented by me
// x.tickDirection = CPTSignPositive;
NSInteger xmajorIncrement = 2;
NSInteger xminorIncrement = 1;
//CGFloat dateCount = [[[CPDStockPriceStore sharedInstance] datesInMonth] count];
CGFloat dateCount = 20;
NSMutableSet *xLabels = [NSMutableSet setWithCapacity:dateCount];
NSMutableSet *xLocations = [NSMutableSet setWithCapacity:dateCount];
NSInteger i = 0;
for (NSString *date in [[CPDStockPriceStore sharedInstance] datesInMonth]) {
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:date textStyle:x.labelTextStyle];
CGFloat location = i++;
// CGFloat location = ++i;
label.tickLocation = CPTDecimalFromCGFloat(location);
label.offset = x.majorTickLength;
if (label) {
[xLabels addObject:label];
[xLocations addObject:[NSNumber numberWithFloat:location]];
}
}
x.axisLabels = xLabels;
x.majorTickLocations = xLocations;
// 4 - Configure y-axis
CPTAxis *y = axisSet.yAxis;
y.title = #"Weight ->";
y.titleTextStyle = axisTitleStyle;
y.titleOffset = -40.0f; //commented by me
y.axisLineStyle = axisLineStyle;
y.majorGridLineStyle = gridLineStyle;
y.labelingPolicy = CPTAxisLabelingPolicyNone;
y.labelTextStyle = axisTextStyle;
y.labelOffset = 16.0f;
y.majorTickLineStyle = axisLineStyle;
y.majorTickLength = 4.0f;
y.minorTickLength = 2.0f;
y.tickDirection = CPTSignPositive;
NSInteger majorIncrement = 40;
NSInteger minorIncrement = 20;
CGFloat yMax = 300.0f; // should determine dynamically based on max price
NSMutableSet *yLabels = [NSMutableSet set];
NSMutableSet *yMajorLocations = [NSMutableSet set];
NSMutableSet *yMinorLocations = [NSMutableSet set];
for (NSInteger j = minorIncrement; j <= yMax; j += minorIncrement) {
NSUInteger mod = j % majorIncrement;
if (mod == 0) {
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:#"%i", j] textStyle:y.labelTextStyle];
NSDecimal location = CPTDecimalFromInteger(j);
label.tickLocation = location;
label.offset = -y.majorTickLength - y.labelOffset;
if (label) {
[yLabels addObject:label];
}
[yMajorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:location]];
} else {
[yMinorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:CPTDecimalFromInteger(j)]];
}
}
y.axisLabels = yLabels;
y.majorTickLocations = yMajorLocations;
y.minorTickLocations = yMinorLocations;
}
#pragma mark - CPTPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
//return [[[CPDStockPriceStore sharedInstance] datesInMonth] count];
return 20;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSInteger valueCount = [[[CPDStockPriceStore sharedInstance] datesInMonth] count];
// NSValue *value = [self.graphData objectAtIndex:index];
// CGPoint point = [value CGPointValue];
switch (fieldEnum) {
case CPTScatterPlotFieldX:
if (index < valueCount) {
//if( [plot.identifier isEqual:CPDTickerSymbolGoal] == YES)
return [NSNumber numberWithUnsignedInteger:index];
}
break;
case CPTScatterPlotFieldY:
if ([plot.identifier isEqual:CPDTickerSymbolActual] == YES ) {
//return [[[CPDStockPriceStore sharedInstance] monthlyPrices:CPDTickerSymbolAAPL] objectAtIndex:index];
if(index < [_graphEmpActualWeightData count]){
// return [_graphEmpActualWeightData objectAtIndex:index];
return (NSDecimalNumber *)[NSDecimalNumber numberWithDouble:[[_graphEmpActualWeightData objectAtIndex:index] doubleValue]];
}
else{
// return (NSNumber *) nil;
}
} else if ([plot.identifier isEqual:CPDTickerSymbolGoal] == YES) {
//return [[[CPDStockPriceStore sharedInstance] monthlyPrices:CPDTickerSymbolGOOG]
//return [_graphEmpGoalWeightData objectAtIndex:index];
return (NSDecimalNumber *)[NSDecimalNumber numberWithDouble:[[_graphEmpGoalWeightData objectAtIndex:index] doubleValue]];
}
break;
}
return [NSDecimalNumber zero];
}
// This does the actual work of creating the plot if we don't already have a graph object.
-(void)initialisePlot
{
// Start with some simple sanity checks before we kick off
if ( (self.hostView == nil) || (self.graphEmpGoalWeightData == nil) ) {
NSLog(#"TUTSimpleScatterPlot: Cannot initialise plot without hosting view or data.");
return;
}
if ( self.graph != nil ) {
NSLog(#"TUTSimpleScatterPlot: Graph object already exists.");
return;
}
[self initPlot];
}
`Hi friends,
I have been struggling with this problem since yesterday. Need your help desperately.
I'm new to core plot and have been facing a crash issue when I try to draw a second plot in the graph. I'm getting different different reasons each time. some of them are pasted below.
1)* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM numberOfRecordsForPlot:]: unrecognized selector sent to instance 0x726adc0'
2)EXC_BAD_ACCESS
3)* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CALayerArray numberOfRecordsForPlot:]: unrecognized selector sent to instance 0x769f5b0'
4)* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDecimalNumber numberOfRecordsForPlot:]: unrecognized selector sent to instance 0x726adc0'
I'm really not getting what went wrong in my code. It is working fine when I

Getting CorePlot bar chart to display float values instead of integers?

Basically, I have this class which I am using to display data in a CorePlot bar chart:
#import "BarChartViewController.h"
#import "AppDelegate.h"
#import "Project.h"
#import "Currency.h"
#import "TotalValueCalculator.h"
#define BAR_POSITION #"POSITION"
#define BAR_HEIGHT #"HEIGHT"
#define COLOR #"COLOR"
#define CATEGORY #"CATEGORY"
#define AXIS_START 0
#interface BarChartViewController ()
#end
#implementation BarChartViewController
{
int count;
}
#synthesize data;
#synthesize graph;
#synthesize hostingView;
#synthesize graphType;
//Finds the maximum value from an array of ints
int findMax (int numbers[], int N){
int max = numbers[0];
for (int i = 0; i < N; i++)
if(max<numbers[i]) max = numbers[i];
return max;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void) generateBarPlot
{
//Create host view
self.hostingView = [[CPTGraphHostingView alloc]
initWithFrame:[[UIScreen mainScreen]bounds]];
[self.view addSubview:self.hostingView];
//Create graph and set it as host view's graph
self.graph = [[CPTXYGraph alloc] initWithFrame:self.hostingView.bounds];
[self.hostingView setHostedGraph:self.graph];
//set graph padding and theme
self.graph.plotAreaFrame.paddingTop = 20.0f;
self.graph.plotAreaFrame.paddingRight = 20.0f;
self.graph.plotAreaFrame.paddingBottom = 170.0f;
self.graph.plotAreaFrame.paddingLeft = 70.0f;
[self.graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
//set axes ranges
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(AXIS_START) length:CPTDecimalFromFloat(50)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat((axisEnd - AXIS_START)+5)];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
//set axes' title, labels and their text styles
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.fontName = #"Helvetica";
textStyle.fontSize = 14;
textStyle.color = [CPTColor whiteColor];
if (graphType == #"TotalProject"){
axisSet.xAxis.title = #"Project Name";
}
else if (graphType == #"TotalCategory"){
axisSet.xAxis.title = #"Category Name";
}
else if (graphType == #"TotalCurrency"){
axisSet.xAxis.title = #"Currency Name";
}
else if (graphType == #"DistanceTravelled"){
axisSet.xAxis.title = #"Project";
}
else if (graphType == #"FuelCostProject"){
axisSet.xAxis.title = #"Project";
}
else if (graphType == #"FuelCostCurrency"){
axisSet.xAxis.title = #"Currency";
}
axisSet.yAxis.title = #"Total Value";
axisSet.xAxis.titleTextStyle = textStyle;
axisSet.yAxis.titleTextStyle = textStyle;
axisSet.xAxis.titleOffset = 50.0f;
axisSet.yAxis.titleOffset = 50.0f;
axisSet.xAxis.labelTextStyle = textStyle;
axisSet.xAxis.labelOffset = 3.0f;
axisSet.yAxis.labelTextStyle = textStyle;
axisSet.yAxis.labelOffset = 3.0f;
//set axes' line styles and interval ticks
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.lineColor = [CPTColor whiteColor];
lineStyle.lineWidth = 3.0f;
axisSet.xAxis.axisLineStyle = lineStyle;
axisSet.yAxis.axisLineStyle = lineStyle;
axisSet.xAxis.majorTickLineStyle = lineStyle;
axisSet.yAxis.majorTickLineStyle = lineStyle;
//Set x axis tick length to 0 as there is no data on the x axis
axisSet.xAxis.majorIntervalLength = CPTDecimalFromFloat(0.0f);
if (axisEnd <= 400){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(25.0f);
}
else if (axisEnd <= 900){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(50.0f);
}
else if (axisEnd <= 1300){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(75.0f);
}
else if (axisEnd <= 1800){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(100.0f);
}
else if (axisEnd <= 2300){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(125.0f);
}
else if (axisEnd <= 2800){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(150.0f);
}
else if (axisEnd <= 3300){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(175.0f);
}
else if (axisEnd <= 3500){
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(200.0f);
}
else {
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(300.0f);
}
axisSet.xAxis.majorTickLength = 7.0f;
axisSet.yAxis.majorTickLength = 7.0f;
axisSet.xAxis.minorTickLineStyle = lineStyle;
axisSet.yAxis.minorTickLineStyle = lineStyle;
axisSet.xAxis.minorTicksPerInterval = 1;
axisSet.yAxis.minorTicksPerInterval = 1;
axisSet.xAxis.minorTickLength = 5.0f;
axisSet.yAxis.minorTickLength = 5.0f;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
[numberFormatter setPositiveFormat:#"###0.00"];
axisSet.yAxis.labelFormatter = numberFormatter;
int initialTickLocation = 9;
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSMutableArray *customTickLocations = [[NSMutableArray alloc] init];
NSMutableArray *xAxisLabels = [[NSMutableArray alloc] init];
if (graphType == #"TotalProject"){
for (int i = 0; i < [appDelegate.projects count]; i++){
//CHANGE THESE NUMBERS TO CHANGE POSITIONS OF THE LABELS
[customTickLocations addObject:[NSNumber numberWithInt:initialTickLocation]];
initialTickLocation = initialTickLocation + 7;
[xAxisLabels addObject:[[appDelegate.projects objectAtIndex:i] name]];
}
}
else if (graphType == #"TotalCategory"){
for (int i = 0; i < [appDelegate.categories count]; i++){
//CHANGE THESE NUMBERS TO CHANGE POSITIONS OF THE LABELS
[customTickLocations addObject:[NSNumber numberWithInt:initialTickLocation]];
initialTickLocation = initialTickLocation + 7;
[xAxisLabels addObject:[[appDelegate.categories objectAtIndex:i] name]];
}
}
else if (graphType == #"TotalCurrency"){
for (int i = 0; i < [appDelegate.currencies count]; i++){
//CHANGE THESE NUMBERS TO CHANGE POSITIONS OF THE LABELS
[customTickLocations addObject:[NSNumber numberWithInt:initialTickLocation]];
initialTickLocation = initialTickLocation + 7;
[xAxisLabels addObject:[[appDelegate.currencies objectAtIndex:i] shortName]];
}
}
else if (graphType == #"DistanceTravelled"){
for (int i = 0; i < [appDelegate.projects count]; i++){
//CHANGE THESE NUMBERS TO CHANGE POSITIONS OF THE LABELS
[customTickLocations addObject:[NSNumber numberWithInt:initialTickLocation]];
initialTickLocation = initialTickLocation + 7;
[xAxisLabels addObject:[[appDelegate.projects objectAtIndex:i] name]];
}
}
else if (graphType == #"FuelCostProject"){
for (int i = 0; i < [appDelegate.projects count]; i++){
//CHANGE THESE NUMBERS TO CHANGE POSITIONS OF THE LABELS
[customTickLocations addObject:[NSNumber numberWithInt:initialTickLocation]];
initialTickLocation = initialTickLocation + 7;
[xAxisLabels addObject:[[appDelegate.projects objectAtIndex:i] name]];
}
}
else if (graphType == #"FuelCostCurrency"){
for (int i = 0; i < [appDelegate.currencies count]; i++){
//CHANGE THESE NUMBERS TO CHANGE POSITIONS OF THE LABELS
[customTickLocations addObject:[NSNumber numberWithInt:initialTickLocation]];
initialTickLocation = initialTickLocation + 7;
[xAxisLabels addObject:[[appDelegate.currencies objectAtIndex:i] shortName]];
}
}
axisSet.xAxis.labelRotation = M_PI/4;
axisSet.xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
NSUInteger labelLocation = 0;
NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
for (NSNumber *tickLocation in customTickLocations){
CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:[xAxisLabels objectAtIndex:labelLocation++] textStyle:axisSet.xAxis.labelTextStyle];
newLabel.tickLocation = [tickLocation decimalValue];
newLabel.offset = axisSet.xAxis.labelOffset + axisSet.xAxis.majorTickLength;
newLabel.rotation = M_PI / 4;
[customLabels addObject:newLabel];
}
axisSet.xAxis.axisLabels = [NSSet setWithArray:customLabels];
// Create bar plot and add it to the graph
CPTBarPlot *plot = [[CPTBarPlot alloc] init] ;
plot.dataSource = self;
plot.delegate = self;
plot.barWidth = [[NSDecimalNumber decimalNumberWithString:#"5.0"]
decimalValue];
plot.barOffset = [[NSDecimalNumber decimalNumberWithString:#"10.0"]
decimalValue];
plot.barCornerRadius = 5.0;
// Remove bar outlines
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor clearColor];
plot.lineStyle = borderLineStyle;
// Identifiers are handy if you want multiple plots in one graph
plot.identifier = #"projectTotals";
[self.graph addPlot:plot];
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return [self.data count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDictionary *bar = [self.data objectAtIndex:index];
if(fieldEnum == CPTBarPlotFieldBarLocation){
NSLog(#"Position: %#", [bar valueForKey:BAR_POSITION]);
return [bar valueForKey:BAR_POSITION];
}
else{
NSLog(#"Height: %#", [bar valueForKey:BAR_HEIGHT]);
return [bar valueForKey:BAR_HEIGHT];
}
}
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index
{
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.fontName = #"Helvetica";
textStyle.fontSize = 12;
textStyle.color = [CPTColor whiteColor];
NSDictionary *bar = [self.data objectAtIndex:index];
//Here we want to display the value for that day, not the name of the day
CPTTextLayer *label = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:#"%0.2f", [[bar valueForKey:BAR_HEIGHT] floatValue]]];
label.textStyle =textStyle;
return label;
}
-(CPTFill *)barFillForBarPlot:(CPTBarPlot *)barPlot
recordIndex:(NSUInteger)index
{
NSDictionary *bar = [self.data objectAtIndex:index];
CPTGradient *gradient = [CPTGradient gradientWithBeginningColor:[CPTColor whiteColor]
endingColor:[bar valueForKey:#"COLOR"]
beginningPosition:0.0 endingPosition:0.3 ];
[gradient setGradientType:CPTGradientTypeAxial];
[gradient setAngle:320.0];
CPTFill *fill = [CPTFill fillWithGradient:gradient];
return fill;
}
- (void)dealloc
{
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.data = [NSMutableArray array];
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
count = [appDelegate.projects count];
int catCount = [appDelegate.categories count];
int currencyCount = [appDelegate.currencies count];
int bar_heights[count];
NSString *categories[count];
int catBar_heights[catCount];
NSString *catCategories[catCount];
int currencyBar_heights[currencyCount];
NSString *currencyCategories[currencyCount];
if ([graphType isEqualToString:#"TotalProject"])
{
for (int i = 0; i < count; i++)
{
TotalValueCalculator *calc = [[TotalValueCalculator alloc] initWithString:[[appDelegate.projects objectAtIndex:i] name]];
NSString *totalValueString = [calc compareProject];
float totalValue = [totalValueString floatValue];
bar_heights[i] = totalValue;
NSLog(#"---%0.2f", totalValue);
categories[i] = [[appDelegate.projects objectAtIndex:i] name];
}
axisEnd = findMax(bar_heights, count) + ((findMax(bar_heights, count)) / 10);
UIColor *colors[] = {
[UIColor colorWithRed:139/255.0 green:198/255.0 blue:63/255.0 alpha:1],
nil};
for (int i = 0; i < [appDelegate.projects count] ; i++){
int position = i*7; //Bars will be 7 pts away from each other
float height = bar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSDecimalNumber numberWithFloat:position],BAR_POSITION,
[NSDecimalNumber numberWithFloat:height],BAR_HEIGHT,
colors[0],COLOR,
categories[i],CATEGORY,
nil];
NSLog(#"^^^^^^^^^^^^^%#", [NSDecimalNumber numberWithFloat:height]);
[self.data addObject:bar];
}
}
else if ([graphType isEqualToString:#"TotalCategory"])
{
for (int i = 0; i < catCount; i++)
{
TotalValueCalculator *calc = [[TotalValueCalculator alloc] initWithString:[[appDelegate.categories objectAtIndex:i] name]];
NSString *totalValueString = [calc compareCategory];
double totalValue = [totalValueString doubleValue];
catBar_heights[i] = totalValue;
catCategories[i] = [[appDelegate.categories objectAtIndex:i] name];
}
axisEnd = findMax(catBar_heights, catCount) + ((findMax(catBar_heights, catCount)) / 10);
UIColor *colors[] = {
[UIColor colorWithRed:236/255.0 green:139/255.0 blue:34/255.0 alpha:1],
nil};
for (int i = 0; i < [appDelegate.categories count] ; i++){
double position = i*7; //Bars will be 7 pts away from each other
double height = catBar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:height],BAR_HEIGHT,
colors[0],COLOR,
catCategories[i],CATEGORY,
nil];
[self.data addObject:bar];
}
}
else if ([graphType isEqualToString:#"TotalCurrency"])
{
for (int i = 0; i < currencyCount; i++)
{
TotalValueCalculator *calc = [[TotalValueCalculator alloc] initWithString:[[appDelegate.currencies objectAtIndex:i] shortName]];
NSString *totalValueString = [calc compareCurrency];
double totalValue = [totalValueString doubleValue];
currencyBar_heights[i] = totalValue;
currencyCategories[i] = [[appDelegate.currencies objectAtIndex:i] shortName];
}
axisEnd = findMax(currencyBar_heights, currencyCount) + ((findMax(currencyBar_heights, currencyCount)) / 10);
UIColor *colors[] = {
[UIColor colorWithRed:236/255.0 green:139/255.0 blue:34/255.0 alpha:1],
nil};
for (int i = 0; i < [appDelegate.currencies count] ; i++){
double position = i*7; //Bars will be 7 pts away from each other
double height = currencyBar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:height],BAR_HEIGHT,
colors[0],COLOR,
currencyCategories[i],CATEGORY,
nil];
[self.data addObject:bar];
}
}
else if ([graphType isEqualToString:#"DistanceTravelled"])
{
for (int i = 0; i < count; i++)
{
TotalValueCalculator *calc = [[TotalValueCalculator alloc] initWithString:[[appDelegate.projects objectAtIndex:i] name]];
NSString *totalValueString = [calc compareProjectDistance];
double totalValue = [totalValueString doubleValue];
bar_heights[i] = totalValue;
categories[i] = [[appDelegate.projects objectAtIndex:i] name];
}
axisEnd = findMax(bar_heights, count) + ((findMax(bar_heights, count)) / 10);
UIColor *colors[] = {
[UIColor colorWithRed:236/255.0 green:139/255.0 blue:34/255.0 alpha:1],
nil};
for (int i = 0; i < [appDelegate.projects count] ; i++){
double position = i*7; //Bars will be 7 pts away from each other
double height = bar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:height],BAR_HEIGHT,
colors[0],COLOR,
categories[i],CATEGORY,
nil];
[self.data addObject:bar];
}
}
else if ([graphType isEqualToString:#"FuelCostProject"])
{
for (int i = 0; i < count; i++)
{
TotalValueCalculator *calc = [[TotalValueCalculator alloc] initWithString:[[appDelegate.projects objectAtIndex:i] name]];
NSString *totalValueString = [calc compareProjectFuel];
double totalValue = [totalValueString doubleValue];
bar_heights[i] = totalValue;
categories[i] = [[appDelegate.projects objectAtIndex:i] name];
}
axisEnd = findMax(bar_heights, count) + ((findMax(bar_heights, count)) / 10);
UIColor *colors[] = {
[UIColor colorWithRed:236/255.0 green:139/255.0 blue:34/255.0 alpha:1],
nil};
for (int i = 0; i < [appDelegate.projects count] ; i++){
double position = i*7; //Bars will be 7 pts away from each other
double height = bar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:height],BAR_HEIGHT,
colors[0],COLOR,
categories[i],CATEGORY,
nil];
[self.data addObject:bar];
}
}
else if ([graphType isEqualToString:#"FuelCostCurrency"])
{
for (int i = 0; i < currencyCount; i++)
{
TotalValueCalculator *calc = [[TotalValueCalculator alloc] initWithString:[[appDelegate.currencies objectAtIndex:i] shortName]];
NSString *totalValueString = [calc compareCurrencyFuel];
double totalValue = [totalValueString doubleValue];
currencyBar_heights[i] = totalValue;
currencyCategories[i] = [[appDelegate.currencies objectAtIndex:i] shortName];
}
axisEnd = findMax(currencyBar_heights, currencyCount) + ((findMax(currencyBar_heights, currencyCount)) / 10);
UIColor *colors[] = {
[UIColor colorWithRed:236/255.0 green:139/255.0 blue:34/255.0 alpha:1],
nil};
for (int i = 0; i < [appDelegate.currencies count] ; i++){
double position = i*7; //Bars will be 7 pts away from each other
double height = currencyBar_heights[i];
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:height],BAR_HEIGHT,
colors[0],COLOR,
currencyCategories[i],CATEGORY,
nil];
[self.data addObject:bar];
}
}
[self generateBarPlot];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
I know theres a lot there, but I just can't figure out for the life of me how I get this bar chart to display float values (for bar heights)? I've spent so much time on this now I'm starting to despair.
Does anyone know how to do this? The values that chart is receiving are definitely float values.
Any help at all would be much appreciated..
Thanks a lot,
Jack
The bar_heights arrays in -viewDidLoad are declared as int. Since the data values are stored here before being placed in the dictionary structure you pass to the plot datasource, any fractional part of the values gets lost.

NSTimer stops when we click on ScrollView

In my app am using UIScrollView which is having UIImageView(20) to add images iused the - (void)populateScrollView method.
- (void)populateScrollView
{
TonifyAppDelegate *appDelegate = (TonifyAppDelegate *)[UIApplication sharedApplication].delegate;
double x1 = 0, y1 = 3;
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSMutableArray *getEffectsImageData = [ud objectForKey:#"getimageeffects"];
imageViewsArray = [[NSMutableArray alloc] initWithCapacity:[getEffectsImageData count]];
for(int i = 0; i < [getEffectsImageData count]; i++)
{
NSString *sfxUrlFileName = [ [getEffectsImageData objectAtIndex:i] lastPathComponent];
NSLog(#"sfxUrlFileName: %#", sfxUrlFileName);
NSData *imageData = [appDelegate readSongDataFromDocsDirectory:sfxUrlFileName];
UIImage *image = [[UIImage alloc] initWithData:imageData];
UIImageView *anImageView = [[UIImageView alloc]initWithImage:image];
CGRect imageFrame = anImageView.frame;
imageFrame.origin.x = x1;
imageFrame.origin.y = y1;
anImageView.frame = CGRectMake(x1, y1, 45, 41);
anImageView.userInteractionEnabled = YES;
[scrollView addSubview:anImageView];
x1 += anImageView.frame.size.width + 3;
if (anImageView && [anImageView isMemberOfClass: [UIImageView class]])
[imageViewsArray addObject: anImageView];
}
NSLog(#"imageViewsArray:%#",imageViewsArray);
}
And to recognize touch in UIScrollView i used
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(singleTapGestureCaptured:)];
[scrollView addGestureRecognizer:singleTap];
Meanwhile am running song by using NSTimer which is like
myTimer = [NSTimer scheduledTimerWithTimeInterval:timeinterval target:self selector:#selector(**updatplayer**) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:myTimer forMode:NSRunLoopCommonModes];
in updatePlayer method am doing task as follows
- (void)updatplayer
{
TonifyAppDelegate *appDelegate = (TonifyAppDelegate *)[UIApplication sharedApplication].delegate;
if (mThresholdVal<mMainLoopLength)
{
mThresholdVal+=0.5;
}
else
{
mThresholdVal = 0.0;
}
if (divimageView)
{
[divimageView removeFromSuperview];
}
if ([self isHeadsetPluggedIn]==NO) {
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
}
else
{
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_None;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
}
NSString *cu=[NSString stringWithFormat:#"%2.f",audioPlayer.currentTime];
NSString *du=[NSString stringWithFormat:#"%2.f",audioPlayer.duration];
NSLog(#"LOOP cu Duration = %#",cu);
NSLog(#"LOOP du = %#",du);
int curenttime=(int)[cu intValue];
NSLog(#"LOOP current Duration = %2.f",audioPlayer.duration);
if(curenttime==0)
{
[audioPlayer play];
x=20;
}
mixdata = [NSMutableDictionary dictionary];
{
[activityIndicator stopAnimating];
activityIndicator.hidden = YES;
[divimageView setFrame:CGRectMake(x, 87, 12, 144)];
[self.view addSubview:divimageView];
x=x+1;
if ((x>19 && x< 480) && appDelegate.songURL != NULL) {
[avplayer play];
NSLog(#"mixdata:%#", mixdata);
}
else if((x>19 && x< 480) && (appDelegate.songIntroUrl || appDelegate.songMidUrl || appDelegate.songChorusUrl) )
{
[audioPlayer play];
}
if (x==xCord && yCord<235)
{
[audioPlayer1 play];
}
if (x==recXcord)
{
recaudioPlayer.volume = 10.0;
[recaudioPlayer play];
[activityIndicator stopAnimating];
activityIndicator.hidden = YES;
}
if(appDelegate.xCordArray!=NULL && [appDelegate.tagArray count]>0)
{
for(int i = 0; i<[appDelegate.xCordArray count];i++)
{
if (i == 0){
NSLog(#"sfxCount in i==0......%d",sfxCount);
NSLog(#"[appDelegate.xCordArray count] in i==0......%d",[appDelegate.xCordArray count]);
NSLog(#"[appDelegate.mMixedSFXTrack2Array count] in i==0......%d",[appDelegate.mMixedSFXTrack2Array count]);
if (sfxCount-1 != [appDelegate.xCordArray count])
{
if ([appDelegate.xCordArray count] > [appDelegate.mMixedSFXTrack2Array count] )
{
mShouldBufferUpdate = TRUE;
sfxCount = [appDelegate.xCordArray count];
}
}
}
if (x==[[appDelegate.xCordArray objectAtIndex:i] intValue] && appDelegate.imgDragXCodr<480)
{
int j = [[appDelegate.tagArray objectAtIndex:i] intValue];
//mShouldBufferUpdate = TRUE;
[self getSetSongData:j :x];
[audioPlayer2 play];
}
}
}
if(appDelegate.xCordTrack3Array!=NULL && [appDelegate.track3tagArray count]>0)
{
for(int i = 0; i<[appDelegate.xCordTrack3Array count];i++)
{
if (i == 0)
{
if (sfxCount3-1 != [appDelegate.xCordTrack3Array count])
{
if ([appDelegate.xCordTrack3Array count] > [appDelegate.mMixedSFXTrack3Array count] )
{
mShouldBuffer3Update = TRUE;
sfxCount3 = [appDelegate.xCordTrack3Array count];
}
}
}
if (x==[[appDelegate.xCordTrack3Array objectAtIndex:i] intValue] && appDelegate.imgDragXCodr1<480)
{
int j = [[appDelegate.track3tagArray objectAtIndex:i] intValue];
[self getSetSongData:j :x];
[trac3AudioPlayer play]; //For SFX Sounds
}
}
}
if (x == 480)
{
x=20;
}
}
}
When i click on scrollView it generates an image in UIView(main View) at that time NSTimer is getting paused.
How can we solve this.
Any one can help or suggest me.
Thanks in advance.

Memory leak in ImagePickerView in iPhone

I am using the Scrollviewer to load images. I get the images from Media Library and save it into local folder. If I select and add images more than 5, app get memory warning level2 app get crash.
This is code to get the Photos from database:
-(NSMutableArray*) GetPhotos:(int)folderId
{
NSString *query =[[[NSString alloc] initWithFormat:#"SELECT * FROM Photo WHERE FolderID = ?"] autorelease];
FMDatabase *db = [self.dbUtils sharedDB];
FMResultSet *rs = [db executeQuery:query, [NSNumber numberWithInt:folderId]];
NSMutableArray *results = [[NSMutableArray alloc] init];
while([rs next]) {
Photo *photo = [[Photo alloc] init];
photo.PhotoID = [rs intForColumn:#"PhotoID"];
photo.FolderID = [rs intForColumn:#"FolderID"];
photo.PhotoName = [rs stringForColumn:#"PhotoName"];
photo.UpdatedDate = [rs stringForColumn:#"UpdatedDate"];
photo.ImageData = [rs dataForColumn:#"ImageData"];
photo.Path = [rs stringForColumn:#"Path"];
photo.isPrivacy = [rs boolForColumn:#"isPrivacy"];
[results addObject:photo];
[photo release];
}
[rs close];
return results;
}
Pick the images from Image picker view controller:
#pragma mark UIImagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[self dismissModalViewControllerAnimated:YES];
PrivacyPixAppDelegate *appDelegate = [PrivacyPixAppDelegate appDelegate];
dispatch_queue_t image_queue;
image_queue = dispatch_queue_create("com.gordonfontenot.app", NULL);
dispatch_async(image_queue, ^{
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *pickedImage = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSString *fileDirectory = [FileUtils documentsDirectoryPath];
fileDirectory = [fileDirectory stringByAppendingFormat:#"/%#/",self.FolderName];
NSString *fileName = [NSString stringWithFormat:#"%#.jpg",[appDelegate newUUID]];
Photo *photo = [[Photo alloc] init];
photo.PhotoName = fileName;
photo.Path = fileDirectory;
photo.FolderID = self.FolderID;
photo.isPrivacy = FALSE;
self.btnEdit.hidden = NO;
fileDirectory = [fileDirectory stringByAppendingFormat:#"%#",fileName];
NSLog(#"FileName:%#",fileName);
NSLog(#"Directory:%#",fileDirectory);
NSData *jpegData = UIImageJPEGRepresentation(pickedImage,5.0);
[jpegData writeToFile:fileDirectory atomically:NO];
PhotoDAO *dao = [[appDelegate daos] sharedPhotoDAO];
[dao AddPhoto:photo];
[photo release];
NSMutableArray *list = [dao GetPhotos:FolderID];
self.listData = list;
[list release];
[self loadForm:self.listData];
});
});
dispatch_release(image_queue);
}
This is method for load images into scrollviewer. This method only problem to memory leak
-(void)loadForm:(NSMutableArray*)list
{
NSMutableArray *photos = [[NSMutableArray alloc] init];
if([list count] == 0)
self.btnEdit.hidden = YES;
else
self.btnEdit.hidden = NO;
for (int Count = 0; Count < [list count] ; Count ++)
{
Photo *photo = [list objectAtIndex: Count];
PhotoView *photoView = [[PhotoView alloc] initWithFrame: CGRectMake(ThumbnailSizeWidth * (Count % THUMBNAIL_COLS) + PADDING * (Count % THUMBNAIL_COLS) + PADDING,
ThumbnailSizeHeight * (Count / THUMBNAIL_COLS) + PADDING * (Count / THUMBNAIL_COLS) + PADDING + PADDING_TOP,
ThumbnailSizeWidth,
ThumbnailSizeHeight)];
[photoView setPhoto:photo];
[photoView setTag:Count];
photoView.showsTouchWhenHighlighted = YES;
photoView.userInteractionEnabled = YES;
photoView.layer.cornerRadius = 8.0;
if([FileUtils fileExistsAtPath:photo.Path fileName:photo.PhotoName])
{
UIImage *tImage= nil;
if(photo.isPrivacy)
tImage = [UIImage imageNamed:#"locked.png"];
else
{
tImage = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#%#",photo.Path,photo.PhotoName]];
MyPhoto *photo = [[MyPhoto alloc] initWithImage:tImage];
[tImage release];
[photos addObject:photo];
[photo release];
}
[photoView setImage:tImage forState:UIControlStateNormal];
[photoView addTarget:self action:#selector(FormClicked:) forControlEvents:UIControlEventTouchUpInside];
photoView.frame = CGRectMake(ThumbnailSizeWidth * (Count % THUMBNAIL_COLS) + PADDING * (Count % THUMBNAIL_COLS) + PADDING,
ThumbnailSizeHeight * (Count / THUMBNAIL_COLS) + PADDING * (Count / THUMBNAIL_COLS) + PADDING + PADDING_TOP,
ThumbnailSizeWidth,
ThumbnailSizeHeight);
[scrollViewer addSubview:photoView];
[photoView release];
}
}
if(source)
[source release];
source = [[MyPhotoSource alloc] initWithPhotos:photos];
[photos release];
CGFloat scrollableHeight = ( ThumbnailSizeHeight / THUMBNAIL_COLS) * [list count] + PADDING;
scrollViewer.contentSize = CGSizeMake(320, scrollableHeight + ( ThumbnailSizeWidth * 2) );
scrollViewer.clipsToBounds = YES;
}
Custom Button Class:
#class Photo;
#interface PhotoView : UIButton {
Photo *photo;
}
#property(nonatomic,retain) Photo *photo;
#end
Where I am not release objects properly? where is the memory leak?. This memory issue is occur when I pick image and loadimages.
memory warning is not memory leak but indicates higher memory usage. Use instrumentation to see where memory growth is happening.