views:

111

answers:

1

My problem is this: I can't seem to access the variable todaysDate from the numberForPlot or numberOfRecordsForPlot functions (see below for numberForPlot), but I can from anywhere else in the file.

The NSLog in the viewDidLoad works perfectly, the date is set correctly. If I access the variable from my own class functions, then that's fine too and it works. However, when I try to access it from numberForPlot I get an error:

Program received signal: “EXC_BAD_ACCESS”.

In my header file, I have the following - note my class implements CPPlotDataSource.

#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"

@interface ResultsGraphViewController : UIViewController <CPPlotDataSource> {
    NSManagedObjectContext *managedObjectContext;
    CPXYGraph *graph;
    NSMutableArray *eventsArray;
    NSDate *todaysDate;
}

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain) NSMutableArray *eventsArray;
@property (nonatomic, retain) NSDate *todaysDate;

- (void)getEvents;
- (void)configureGraph;

@end

In the implementation file, I have (relevant highlights only):

@synthesize managedObjectContext;
@synthesize eventsArray;
@synthesize todaysDate;

and

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setTitle:@"Results"];

    todaysDate = [NSDate date];
    NSLog(@"Set today's date to %@", todaysDate);
    [self getEvents];
    [self configureGraph];
}

and

-(NSNumber *)numberForPlot:(CPPlot *)plot 
 field:(NSUInteger)fieldEnum 
 recordIndex:(NSUInteger)index 
{ 
NSLog(@"%d events in the array.", [eventsArray count]);
NSLog(@"today's date is %@.", todaysDate);

...

}

(in the last two lines, above, the number of events in the array is output successfully, but the last line causes the error).

Any ideas as to why this is a problem, and how I can get around it? I imagine it's something to do with being the CPPlotDataSource - how does this affect scoping?

Or do I just have an error in my code? All help much appreciated!

+2  A: 

The problem is that [NSDate date] returns an autoreleased object, which you don't hold on to. It will hang around until the end of the current cycle of the run loop (why it doesn't crash immediately in your first NSLog() statement), then it will be released. When you try to access it in -numberForPlot:, it has been released and your application crashes.

To fix this, change the line in -viewDidLoad to read

self.todaysDate = [NSDate date];

You defined todaysDate to be a property with the retain attribute, so this will retain your date. Just remember to add a [todaysDate release] in your -dealloc method to prevent a leak.

Brad Larson
Perfect! Thanks for the fix, and the explanation.
David Conlisk