开发者

Delaying an -(id)init instance; is it possible?

开发者 https://www.devze.com 2023-04-05 10:12 出处:网络
I\'ve been trying to get a PDF from an NSURL that is changed during a - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I've been trying to get a PDF from an NSURL that is changed during a

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

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

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 = CGPDFDocumentCre开发者_开发百科ateWithURL((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.

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];
}

Meanwhile the UI should display an activity indicator.

The MyPDFModelDelegate protocol should have two methods:

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

YourPDFWrapperClass is used to return an autoreleased document.

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.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消