我有一个单例类可以从网络上下载一些数据。我正在从 GCD 队列中的其他类“A”调用单例类的下载方法,然后下载开始。同时,我还在 GCD 队列中的类“B”中执行此下载方法。在这种情况下,我想通知“B”类等待下载完成。下载完成后,也将下载数据的副本提供给“B”类。这里我试图从A和B两个类下载同一个文件,否则我的实现没有问题。怎么可能?
意思是我在不同的线程中调用相同的方法。那么我如何向线程 B 发出信号,告知线程 A 正在下载相同的文件,并在完成后将数据也传递给线程 B
- (NSData *)Download:(NSString *)urlString{
// here I am doing all the downloading operations
return data;
}
最佳答案
下载器.h
// Signature of a block that is called with the downloaded data from a URL
// when the download is complete
typedef (void)(^)(NSData *) DownloadCompletedBlock;
// Public interface of a class that downloads data from URLs
// Downloads take place on a private dispatch queue, which
// downloads URLs one at a time
// Previously downloaded URLs are cached in a dictionary
// Every so often the cache should be processed to discard old
// entries. This will stop the cache from growing too large.
// Since all downloads happen on the same dispatch queue,
// accesses to the cache are naturally serialized without the need
// for a lock
@interface Downloader : NSObject
// Download the contents of a URL
// When the download is complete downloadCompleted will
// be executed on the callbackQueue to pass the downloaded
// data as a result
// This is the method that thread A should call
- (void)download:(NSString *)URLString
calbackQueue:(dispatch_queue_t)callbackQueue
completionBlock:(DownloadCompletedBlock)downloadCompleted;
// Download the contents of a URL blocking the thread that calls the
// method
- (NSData *)downloadBlocking:(NSString *)URLString;
@end
下载器.m
// Private implementation interface
@interface Downloader ()
// The thread/queue on which all downloads take place
@property (readwrite, atomic) dispatch_queue_t downloadQueue;
// A cache of previously downloaded URLs
@property (readwrite, atomic) NSMutableDictionary *cachedDownloads;
// Download the contents of a URL and cache them
- (NSData *)downloadAndCacheUrl:(NSString *)URLString;
@end
// Implementation
@implementation Downloader
// Create the download queue and cache
- (id)init {
self = [super init];
if (self) {
downloadQueue = dispatch_queue_create("downloadQueue", NULL);
self.cachedDownloads = [NSMutableDictionary dictionary];
}
return self;
}
// Download the URL aynchronously on the download queue.
// When the download completes pass the result to the callback queue
// by calling downloadCompleted on the callback queue
- (void)download:(NSString *)URLString
calbackQueue:(dispatch_queue_t)callbackQueue
completionBlock:(DownloadCompletedBlock)downloadCompleted {
dispatch_async(self.downloadQueue, ^{
NSData *downloadedData = [self downloadAndCacheUrl:URLString];
dispatch_async(callbackQueue, ^{
downloadCompleted(downloadedData);
});
});
}
// Download the data blocking the calling thread
// Use a block variable to store the result
// Since the downloaded data is immutable, we do not need
// to worry about synchronizing it or copying it
// Use dispatch_sync to wait until the result is available
// If the data is already in the cache because thread A downloaded it
// then the cached data is used.
// Since downloads happen serially, there is only ever one download happening
// at a time so the download will only happen once
- (NSData *)downloadBlocking:(NSString *)URLString {
__block NSData *downloadedData = nil;
dispatch_sync(self.downloadQueue, ^{
downloadedData = [self downloadAndCacheUrl:URLString];
});
return downloadedData;
}
// Download the content of a URL. If the data has already been
// downloaded and cached, then use the cached value
- (NSData *)downloadAndCacheUrl:(NSString *)URLString {
NSURL *URL = [NSURL URLWithString:*)URLString];
NSData *downloadedData = [self.cachedDownloads objectForKey:URL];
if (downloadedData) {
return downloadedData;
}
downloadedData = [NSData dataWithContentsOfURL:URL];
if (downloadedData) {
[self.cachedDownloads setObject:downloadedData forKey:URL];
}
}
@end
希望这足够清楚
关于objective-c - 我如何通知一个线程等待下载完成,然后将数据传递给等待线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8397601/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta