while循环后运行NSURLConnection

时间:2014-05-14 22:04:41

标签: ios nsurlconnection

我正在尝试从我创建的自定义类中调用一个方法,在其中调用NSURLConnection,但我的NSURLConnection似乎没有执行。

这是我的代码:

int a = 0;

while(a < 10)
{
   a++;
}

if (a == 10)
{
    NSString *q = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://localhost/myURL.txt"] encoding:NSUTF8StringEncoding error:nil];
    NSURLRequest *url = [NSURLRequest requestWithURL:[NSURL URLWithString:q]];
    NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:url delegate:self];
}

上面的代码应该从txt文件中获取一个url并调用它,当它被调用时,它必须创建一个新目录,但事实并非如此。

1 个答案:

答案 0 :(得分:0)

您必须启动连接:

NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:requestURL 
                                                     delegate:self 
                                             startImmediately:YES];

或:

NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:requestURL 
                                                     delegate:self];

然后,如果您希望收到此对象的事件,请务必使您的协议符合协议NSURLConnectionDelegate, NSURLConnectionDataDelegate。所以在你的文件头(.h)中:

@interface YourClass <NSURLConnectionDelegate, NSURLConnectionDataDelegate>

并在您的文件实现(.m)中,例如,您可以编写连接完成加载时调用的方法:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    //your code
}

您将在Apple文档中看到其他委托方法。

如果你想在另一个线程中运行它,你应该在主线程中运行该方法,然后将队列传递给URLConnection:

NSOperationQueue *networkOperationsQueue = [NSOperationQueue new];

NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:requestURL 
                                                     delegate:self 
                                             startImmediately:NO];
[c setDelegateQueue:networkOperationsQueue];
[c start];

无论如何,上面的代码都是多余的:

while(a < 10)
{
   a++;
}

if (a == 10)

如果你在while cycle并等待a == 10暂时出去,你不需要检查是否有等于10 ..因为是这样。

相关问题