NSURLConnection委托和线程 - iPhone [英] NSURLConnection delegation and threading - iPhone

查看:146
本文介绍了NSURLConnection委托和线程 - iPhone的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,通过NSURLConnection更新应用程序文档目录中的两个.plist文件。该类充当NSURLConnection的自己的委托。它工作正常,当我要求一个单一的文件,但失败,当我尝试更新两个文件。是否应该为每个getNewDatabase消息启动一个新的线程?

I have a class that updates two .plist files in the app documents directory via an NSURLConnection. The class acts as its own delegate for NSURLConnection. It works properly when I ask for a single file, but fails when I try to update two files. Does it look like I should start a new thread for each of the getNewDatabase messages?

- (void)getAllNewDatabases {
    [self performSelectorOnMainThread:@selector(getNewDatabase:) withObject:@"file1" waitUntilDone:YES];
    [self performSelectorOnMainThread:@selector(getNewDatabase:) withObject:@"file2" waitUntilDone:YES];
}

- (BOOL)getNewDatabase:(NSString *)dbName
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSMutableString *apiString = [[NSMutableString alloc] initWithString:kAPIHost];
    [apiString appendFormat:@"/%@.plist",dbName];
    NSURLRequest *myRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:apiString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    NSURLConnection *myConnection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:self];
    [apiString release];
    if( myConnection )
    {
        //omitted for clarity here
    }
    [pool release];
}
//NSURLConnection delegate methods here ...


推荐答案

我发现了一些有趣的NSURLConnection和NSThread - 线程将只活着,只要它需要执行你从它调用的方法。

I found something interesting with NSURLConnection and NSThread - the thread will only live as long as it takes to perform the method that you call from it.

在上面的例子中,只有 getNewDatabase:(NSString *)dbName ,因此在实际有时间做任何事情之前就要杀掉它的任何委托方法。

In the case above the thread will live only as long as getNewDatabase:(NSString *)dbName takes to complete, therefore killing off any of its delegate methods before they actually have time to do anything.

我发现网站提供了更好的解释和解决问题

I found this website that gives a better explanation and a solution to the problem

我调整了一点所以我可以有一个自定义时间,如果它没有完成在给定的时间框架(方便,当有人在接入点之间走动时)

I tweaked it a little bit so I could have a custom time out if it didn't complete in a given time frame (handy when someone is walking around between access points)

    start = [NSDate dateWithTimeIntervalSinceNow:3];

    while(!isFinished && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode 
                                                  beforeDate:[NSDate distantFuture]]){

    if([start compare:[NSDate date]] == NSOrderedAscending){
        isFinished = YES;
    }
}

这篇关于NSURLConnection委托和线程 - iPhone的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆