草庐IT

ios - NSURLConnection 在两次后崩溃

coder 2024-01-19 原文

我正在使用下面的地址下载一个 mp3 文件。我有一个 uitoolbarbutton,当点击这个按钮时,我调用 downloadandCreatePath,然后它创建一个包含我的`downloadProgressV' 和一个用于取消下载的 UIButton 的 View 。

我单击下载 View 出现并下载。下载成功完成,如果我取消,它也能正常工作。

问题是如果我做第二次然后第三次。该应用程序第三次崩溃,并在我的 appdelegate 上显示 EXC_BAD_ACCESS 消息。

NSURLResponse *urlResponse;
NSMutableData *downloadedMutableData;
NSURLConnection *connectionManager;

- (NSString *) downloadandCreatePath: (int) doaId
{
    @try {

        self.downloadProgressV.progress=0.0;

        self.downloadView.hidden=NO;


        NSString *stringURL = @"http://www.ergmusic.com/mp3-samples/488000/488799.mp3";

        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:stringURL]
                                                    cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                timeoutInterval:60.0];

        connectionManager = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];

        if (!connectionManager) {
            // Release the receivedData object.
            downloadedMutableData = nil;
            // Inform the user that the connection failed.
        }

    }
    @catch (NSException *exception) {
        NSLog(@"buuuuuuug");
        return @"";
    }
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [downloadedMutableData setLength:0];
    urlResponse = response;
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [downloadedMutableData appendData:data];
    self.downloadProgressV.progress = ((100.0/urlResponse.expectedContentLength)*downloadedMutableData.length)/100;
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    connectionManager = nil;
    downloadedMutableData = nil;
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

    self.downloadProgressV.progress=0.0;
    self.downloadView.hidden = YES;
    connectionManager = nil;
    downloadedMutableData = nil;

}

- (IBAction)cancelDownloadTouchUpInside:(id)sender {
    self.downloadView.hidden=YES;
    [connectionManager cancel];
    connectionManager = nil;
    downloadedMutableData = nil;
}

有人知道我的问题在哪里吗?

更新

我尝试使用以下指令使用 nszombies 调试应用程序:

http://michalstawarz.pl/2014/02/22/debug-exc_bad_access-nszombie-xcode-5/

但这次错误不一致。

更新

我在 viewdidload 方法中实例化了 NSMutableData

我也尝试在 downloadandCreatePath 的第一行实例化它,但我仍然看到错误。

更新 错误发生在 2 次运行 之后,当我想尝试初始化 connectionManager 时。我想知道为什么在两次运行和第三次尝试后会出现问题。为什么它在第一次运行和第二次尝试后都没有运行?!!

更新

我认为下面的堆栈跟踪更好:

    <_NSCallStackArray 0x94ee270>(
0   ???                                 0x097c85cf 0x0 + 159155663,
1   MafatihTebyan                       0x00010cb4 -[DoaShowViewController downloadandCreatePath:] + 404,
2   MafatihTebyan                       0x000114be -[DoaShowViewController DisplayDoaPlayView:] + 94,
3   libobjc.A.dylib                     0x0181f874 -[NSObject performSelector:withObject:withObject:] + 77,
4   UIKit                               0x0057d0c2 -[UIApplication sendAction:to:from:forEvent:] + 108,
5   UIKit                               0x00851c9b -[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 139,
6   libobjc.A.dylib                     0x0181f874 -[NSObject performSelector:withObject:withObject:] + 77,
7   UIKit                               0x0057d0c2 -[UIApplication sendAction:to:from:forEvent:] + 108,
8   UIKit                               0x0057d04e -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 61,
9   UIKit                               0x006750c1 -[UIControl sendAction:to:forEvent:] + 66,
10  UIKit                               0x00675484 -[UIControl _sendActionsForEvents:withEvent:] + 577,
11  UIKit                               0x00674733 -[UIControl touchesEnded:withEvent:] + 641,
12  UIKit                               0x005ba51d -[UIWindow _sendTouchesForEvent:] + 852,
13  UIKit                               0x005bb184 -[UIWindow sendEvent:] + 1232,
14  UIKit                               0x0058ee86 -[UIApplication sendEvent:] + 242,
15  UIKit                               0x0057918f _UIApplicationHandleEventQueue + 11421,
16  CoreFoundation                      0x01a1383f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15,
17  CoreFoundation                      0x01a131cb __CFRunLoopDoSources0 + 235,
18  CoreFoundation                      0x01a3029e __CFRunLoopRun + 910,
19  CoreFoundation                      0x01a2fac3 CFRunLoopRunSpecific + 467,
20  CoreFoundation                      0x01a2f8db CFRunLoopRunInMode + 123,
21  GraphicsServices                    0x0303b9e2 GSEventRunModal + 192,
22  GraphicsServices                    0x0303b809 GSEventRun + 104,
23  UIKit                               0x0057bd3b UIApplicationMain + 1225,
24  MafatihTebyan                       0x00008a2d main + 141,
25  libdyld.dylib                       0x03c1d725 start + 0,
26  ???                                 0x00000001 0x0 + 1
)

重要更新

我注意到即使在第一次调用时代码也无法在 iOS 6 上运行。在 iOS 6 中它总是崩溃。

更新

我看到的所有 NSURLConnection 示例都使用 viewdidload 创建请求文件。我在一个方法中使用它并一次又一次地调用这个方法。因为 url 在每次调用时都在变化。请问这个问题?

最佳答案

如果您在第一次下载完成之前启动第二次下载,如果您重新实例化 NSMutableData(您没有向我们展示),旧的 NSMutableData 将被释放,导致与僵尸相关的错误。您要么需要维护一个 NSMutableData 对象数组,要么为每次下载实例化一个新的委托(delegate)对象。

关于ios - NSURLConnection 在两次后崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24229876/

有关ios - NSURLConnection 在两次后崩溃的更多相关文章

  1. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  2. Ruby Readline 在向上箭头上使控制台崩溃 - 2

    当我在Rails控制台中按向上或向左箭头时,出现此错误:irb(main):001:0>/Users/me/.rvm/gems/ruby-2.0.0-p247/gems/rb-readline-0.4.2/lib/rbreadline.rb:4269:in`blockin_rl_dispatch_subseq':invalidbytesequenceinUTF-8(ArgumentError)我使用rvm来管理我的ruby​​安装。我正在使用=>ruby-2.0.0-p247[x86_64]我使用bundle来管理我的gem,并且我有rb-readline(0.4.2)(人们推荐的最少

  3. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  4. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  5. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  6. ruby-on-rails - Rake 任务仅调用一次时执行两次 - 2

    我写了一个非常简单的rake任务来尝试找到这个问题的根源。namespace:foodotaskbar::environmentdoputs'RUNNING'endend当在控制台中执行rakefoo:bar时,输出为:RUNNINGRUNNING当我执行任何rake任务时会发生这种情况。有没有人遇到过这样的事情?编辑上面的rake任务就是写在那个.rake文件中的所有内容。这是当前正在使用的Rakefile。requireFile.expand_path('../config/application',__FILE__)OurApp::Application.load_tasks这里

  7. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  8. ruby-on-rails - 多次选择一个随机数,但绝不会两次选择相同的随机数 - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:HowdoIgeneratealistofnuniquerandomnumbersinRuby?我想做的事:Random.rand(0..10).timesdoputsRandom.rand(0..10)end但如果随机数已经显示过,则无法再次显示。如何最轻松地做到这一点?

  9. ruby - 在多个线程中引用类方法会导致自动加载循环依赖崩溃 - 2

    代码:threads=[]Thread.abort_on_exception=truebegin#throwexceptionsinthreadssowecanseethemthreadseputs"EXCEPTION:#{e.inspect}"puts"MESSAGE:#{e.message}"end崩溃:.rvm/gems/ruby-2.1.3@req/gems/activesupport-4.1.5/lib/active_support/dependencies.rb:478:inload_missing_constant':自动加载常量MyClass时检测到循环依赖稍加研究后,

  10. ruby - 为 IO::popen 拯救 "command not found" - 2

    当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby​​1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#

随机推荐