2010-05-13 67 views
0

我的問題是這樣的:我似乎無法從numberForPlot或numberOfRecordsForPlot函數訪問變量todaysDate(請參閱下面的numberForPlot),但我可以從文件中的任何其他位置。NumberForPlot函數核心繪圖範圍問題

viewDidLoad中的NSLog工作正常,日期設置正確。如果我從我自己的類函數訪問變量,那麼也沒問題,它可以工作。然而,當我嘗試從numberForPlot訪問它,我得到一個錯誤:

Program received signal: 「EXC_BAD_ACCESS」.

在我的頭文件中,我有以下幾點 - 注意我的類實現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 

在實現文件中,我有(相關亮點只):

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

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    [self setTitle:@"Results"]; 

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

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

... 

} 

(在最後兩行,上面,數組中的事件數是o utput成功,但最後一行導致錯誤)。

任何想法爲什麼這是一個問題,以及如何解決它?我想這與做CPPlotDataSource有關 - 這是如何影響範圍的?

或者我只是在我的代碼中有錯誤?所有幫助非常感謝!

回答

2

問題是,[NSDate date]返回一個自動釋放的對象,你不堅持。它會一直運行直到當前循環結束(爲什麼它不會立即在第一條語句中崩潰),那麼它將被釋放。當您嘗試在-numberForPlot:中訪問它時,它已被釋放並且您的應用程序崩潰。

爲了解決這個問題,改變線-viewDidLoad閱讀

self.todaysDate = [NSDate date]; 

您定義todaysDate要與retain屬性的屬性,所以這將保留您的日期。請記住在您的-dealloc方法中添加[todaysDate release]以防止泄漏。

+0

完美!感謝修復和解釋。 – 2010-05-14 10:56:17