0
我已將我的數據庫填充代碼添加到線程方法。但是,有時候他們可能沒有任何數據要顯示在圖表中。我不想運行查詢兩次,以前一次檢查是否有任何數據,並且我不想在線程函數之前預先填充圖形點。iphone,如果我可以'在線程函數中填充,我該如何退出?
我已經在下面標記了我的填充代碼。
我認爲我唯一的選擇是退出線程功能,但我有點擔心,我想正確地做到這一點,我需要做什麼?
#import "GraphController.h"
@implementation GraphPoint
- (id) initWithID:(int)pkv value:(NSNumber*)number{
if(self = [super init]){
pk = pkv;
value = [number retain];
}
return self;
}
- (NSNumber*) yValue{
return value;
}
- (NSString*) xLabel{
return [NSString stringWithFormat:@"%d",pk];
}
- (NSString*) yLabel{
return [NSString stringWithFormat:@"%d",[value intValue]];
}
@end
@implementation GraphController
- (void)viewDidLoad{
[super viewDidLoad];
graph.title.text = @"Graph View";
[graph setPointDistance:15];
indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGRect r = indicator.frame;
r.origin = self.view.bounds.origin;
r.origin.x = self.view.bounds.size.width/2 - r.size.width/2;
r.origin.y = self.view.bounds.size.height/2 - r.size.height/2;
indicator.frame = r;
[self.view addSubview:indicator];
[indicator startAnimating];
data = [[NSMutableArray alloc] init];
[NSThread detachNewThreadSelector:@selector(thread) toTarget:self withObject:nil];
}
- (void) thread{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//HERE
srand([[NSDate date] timeIntervalSince1970]);
for(int i=0;i<100;i++){
int no = rand() % 100 + i;
GraphPoint *gp = [[GraphPoint alloc] initWithID:i value:[NSNumber numberWithFloat:no]];
[data addObject:gp];
[gp release];
}
[self performSelectorOnMainThread:@selector(threadComplete) withObject:nil waitUntilDone:NO];
[pool drain];
}
- (void) threadComplete{
[indicator stopAnimating];
[self.graph setGraphWithDataPoints:data];
self.graph.goalValue = [NSNumber numberWithFloat:30.0];
self.graph.goalShown = YES;
[self.graph scrollToPoint:80 animated:YES];
[self.graph showIndicatorForPoint:75];
}
- (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.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[data release];
[indicator release];
[super dealloc];
}
@end
很酷,如果我想顯示一個提醒,說'對不起,沒有數據'我該在哪裏放?所以最重要的是我需要跳過這一行'[self performSelectorOnMainThread:@selector(threadComplete)withObject:nil waitUntilDone:NO];' – Jules 2010-10-11 10:52:30
如果你想做任何與UI相關的東西,你需要在主線程上做。所以我會創建一個'showSorryAlert'方法,並在你的線程方法中,用'performSelectorOnMainThread:withObject:waitUntilDone:'和'goto out;':-)調用該方法 – DarkDust 2010-10-11 11:43:20
不幸的是,不調用threadComplete並不會停止顯示圖形。如果你看到代碼,可能會更容易http://github.com/devinross/tapkulibrary – Jules 2010-10-11 13:31:17