如何为iphone中的任何功能调用线程

时间:2011-06-29 11:23:40

标签: iphone objective-c

请帮我解决一下如何在应用程序启动时在iphone上启动后台线程  在我的sqlite数据库表中,我有一个列同步状态。我有3个值0,1,3.i必须在数据库表上调用这些值。表示应用程序已将数据同步到server.if数据库中的任何数据是将同步状态更改更新为1和3表示正在向服务器发送数据,即同步正在进行中。

3 个答案:

答案 0 :(得分:0)

//创建请求。

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]
                    cachePolicy:NSURLRequestUseProtocolCachePolicy
                timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
}

然后实现NSURLConnection的委托方法

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
if(!receivedData){
   receivedData = [[NSMutableData alloc]init];
}
[receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// release the connection, and the data object
[connection release];
// receivedData is declared as a method instance elsewhere
[receivedData release];

// inform the user
NSLog(@"Connection failed! Error - %@ %@",
      [error localizedDescription],
      [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
// receivedData is declared as a method instance elsewhere
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);

// release the connection, and the data object
[connection release];
[receivedData release];
}

希望这有帮助

答案 1 :(得分:0)

您可以使用NSThread类方法启动新的thread.e.g。

[NSThread detachNewThreadSelector:@selector(newThread) toTarget:self withObject:nil];



///////

-(void)newThread{
   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

   ///your code

   [pool release];

}

更多阅读Thread Programming guide

答案 2 :(得分:0)

使用NSInvocation轻松完成后台启动线程,您需要知道的是here

有GCD但每个都有自己的