延迟 -(id)init 实例;是否可以?
我一直在尝试从 NSURL 获取 PDF,该 NSURL
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
在 NSURL 日志中的更改完美记录期间发生更改,但在应用程序有机会对该更改采取行动之前加载了视图。有没有办法通过简单地将代码移动到该部分来延迟读取 URL 更改
viewDidLoad
,或者我是否必须彻底更改所有内容?这是我的 -(id)init 方法:
- (id)init {
if (self = [super init]) {
CFURLRef pdfURL = (CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:appDelegate.baseURL ofType:@"pdf"]];
pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
}
return self;
}
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 = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
}
return self;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您需要使用网络时,经过验证的方法是使用异步调用。这是由网络连接的性质决定的;它是不可预测的,并不总是可靠的,从服务器获取结果所需的时间可能从毫秒到几分钟不等。
我将使用异步方法创建一个数据模型类 MyPDFModel,该类应该运行一个线程以从服务器获取文件:
同时 UI 应该显示一个活动指示器。
MyPDFModelDelegate 协议应该有两个方法:
YourPDFWrapperClass
用于返回自动发布的文档。委托可以让 UI 知道数据已更新,例如,如果委托是数据模型的一部分,则通过发布通知。
这只是一个例子,根据您的需求,实现可能会有所不同,但我想您会明白的。
PS 延迟 init 是一个非常糟糕的主意。
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:
Meanwhile the UI should display an activity indicator.
The MyPDFModelDelegate protocol should have two methods:
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.