延迟-(id)init实例;可能吗? [英] Delaying an -(id)init instance; is it possible?

查看:97
本文介绍了延迟-(id)init实例;可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试从在

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

NSURL中的更改记录得很好,但是在应用程序有机会对更改进行操作之前已加载视图。有没有一种方法可以通过简单地将代码移至

The change in NSURL logs perfectly, but the view is loaded before the app has a chance to act upon that change. Is there a way to delay the reading of the change in URL by simply moving the code to the

viewDidLoad

部分,还是我必须彻底更改所有内容?这是我的-(id)init方法:

section, or do I have to drastically change everything? Here's my -(id)init method:

- (id)init {
if (self = [super init]) {
    CFURLRef pdfURL = (CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:appDelegate.baseURL ofType:@"pdf"]];
    pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
}
return self;

}

推荐答案

当您需要使用网络时,行之有效的方法是使用异步调用。这是因为网络连接的性质。这是不可预测的,并不总是可靠的,从服务器获取结果所花费的时间可能从毫秒到分钟不等。

When you need to work with network the proven approach is to use asynchronous calls. This is because of the nature of a network connection; it is unpredictable, not always reliable, the time you need to spend to get the result from the server can vary from millisecond to minutes.

我将创建一个数据模型类,MyPDFModel,具有异步方法,应运行一个线程以从服务器获取文件:

I would make a data model class, MyPDFModel, with an asynchronous method, that should run a thread to get the file from the server:

- (void)requestPDFWithURL:(NSURL*)fileURL
{
    [NSThread detachNewThreadSelector:@selector(requestPDFWithURLThreaded:) toTarget:self fileURL];
}

- (void)requestPDFWithURLThreaded:(NSURL*)fileURL
{
    NSAutoreleasePool* pool = [NSAutoreleasePool new];
    // do whatever you need to get either the file or an error
    if (isTheFileValid)
        [_delegate performSelectorOnMainThread:@selector(requestDidGetPDF:) withObject:PDFFile waitUntilDone:NO];
    else
        [_delegate performSelectorOnMainThread:@selector(requestDidFailWithError:) withObject:error waitUntilDone:NO];

    [pool release];
}

同时,UI应显示活动指示器。

Meanwhile the UI should display an activity indicator.

MyPDFModelDelegate协议应具有两种方法:

The MyPDFModelDelegate protocol should have two methods:

- (void)requestDidGetPDF:(YourPDFWrapperClass*)PDFDocument;
- (void)requestDidFailWithError:(NSError*)error;

YourPDFWrapperClass 用于返回自动发布的文档

YourPDFWrapperClass is used to return an autoreleased document.

委托可以让UI知道数据已更新,例如,如果委托是数据模型的一部分,则通过发布通知。

The delegate can let the UI know that the data has been updated, for example by posting a notification if the delegate is a part of the data model.

这只是一个示例,具体实现可以根据您的需要而有所不同,但是我想您会明白的。

This is just an example, the implementation can be different depending on your needs, but I think you will get the idea.

PS延迟初始化是一个非常糟糕的主意。

P.S. Delaying an init is a very bad idea.

这篇关于延迟-(id)init实例;可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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