jjzjj

IOS - 递归函数离开内存分配

coder 2024-01-16 原文

我有一个测试应用程序,我在这个应用程序中拥有的是通过 PHP 脚本进行的调用,一旦数据返回,递归调用就会一次又一次地调用 PHP 脚本,依此类推:

发生的事情是每次 [Self recusiveForumActivity];被调用时,我分配了 300kb 的内存,并且在调用此递归方法时内存使用量不断攀升。如果我删除该方法,内存使用量将保持稳定。我怎样才能克服这个问题,以便在每次调用递归方法时都不会丢失内存分配?

这是代码:

//
        //  ViewController.m
        //  Test
        //
        //  Created by trikam patel on 30/06/2015.
        //  Copyright (c) 2015 trikam patel. All rights reserved.
        //

        #import "ViewController.h"

        @interface ViewController ()

        @end

        @implementation ViewController


        -(NSString*)setupPhpCall:(NSString*)requestString :(NSString*)sciptPage{

            //NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:0];
            //[NSURLCache setSharedURLCache:sharedCache];


            NSHTTPURLResponse *urlresponse = nil;
            NSError *error = nil;
            NSString *response = @"";
            NSData *myRequestData = nil;
            NSMutableURLRequest *request = nil;
            NSData *returnData = nil;

            myRequestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];

            //Create your request string with parameter name as defined in PHP file
            request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithFormat: @"http://www.hugt.co.uk/%@", sciptPage]]];
            // set Request Type
            [request setHTTPMethod: @"POST"];
            // Set content-type
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
            // Set Request Body
            [request setHTTPBody: myRequestData];
            // Now send a request and get Response
            //NSHTTPURLResponse* urlResponse = nil;
            //NSError *error = nil;

            //if(tmpArray.count == 0){
            returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlresponse error: &error];
            response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
            //}
            // Log Response
            urlresponse = nil;
            error = nil;
            myRequestData = nil;
            request = nil;
            returnData = nil;

            //NSLog(@"%@",response);/****/
            //[sharedCache removeAllCachedResponses];
            if(response != nil){

            return response;
            }

            return nil;
        }

        -(void)recurseForumActivity{
            dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

            dispatch_async(concurrentQueue, ^{


            __block NSString *myRequestStringForum = [NSString stringWithFormat:@"lastDate=%@&threadTitle=%@&threadCountry=%@&threadCategory=%@&threadSubCategory=%@&getData=0",@"",@"", @"", @"", @""];
            __block NSString *responseForum = [self setupPhpCall:myRequestStringForum :@"getThreadRecurse.php"];


            dispatch_async(dispatch_get_main_queue(), ^{

                dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

                dispatch_async(concurrentQueue, ^{

                dispatch_async(dispatch_get_main_queue(), ^{
                    [NSThread sleepForTimeInterval:2.0f];
                    responseForum = @"";
                    myRequestStringForum = @"";
                    [self recurseForumActivity];
                });
                });

            });

            });

        }

        - (void)viewDidLoad {
            [super viewDidLoad];
            [self recurseForumActivity];
            // Do any additional setup after loading the view, typically from a nib.
        }

        - (void)didReceiveMemoryWarning {
            [super didReceiveMemoryWarning];
            // Dispose of any resources that can be recreated.
        }

        @end

最佳答案

尝试使用 [object performSelector:method] 而不是递归调用。递归函数必须始终具有基本/退出条件,而您的代码没有任何此类条件。所以你不能在这里进行任何递归调用。

- (void)recurseForumActivity{
    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(concurrentQueue, ^{

        __block NSString *myRequestStringForum = [NSString stringWithFormat:@"lastDate=%@&threadTitle=%@&threadCountry=%@&threadCategory=%@&threadSubCategory=%@&getData=0",@"",@"", @"", @"", @""];
        __block NSString *responseForum = [self setupPhpCall:myRequestStringForum :@"getThreadRecurse.php"];

        YourClass * __weak weakSelf = self;

        dispatch_async(dispatch_get_main_queue(), ^{

            dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

            dispatch_async(concurrentQueue, ^{

                dispatch_async(dispatch_get_main_queue(), ^{
                    responseForum = @"";
                    myRequestStringForum = @"";
                    [weakSelf performSelector:@selector(recurseForumActivity) withObject:nil afterDelay:2.0f];
                });
            });

        });

    });
}

关于IOS - 递归函数离开内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31149404/

有关IOS - 递归函数离开内存分配的更多相关文章

  1. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  2. ruby - 如何离开加入Arel? - 2

    Arel3.0.2提供了两个类来指定连接类型:Arel::Nodes::InnerJoin和Arel::Nodes::OuterJoin并使用InnerJoin默认。foo=Arel::Table.new('foo')bar=Arel::Table.new('bar')foo.join(bar,Arel::Nodes::InnerJoin)#innerfoo.join(bar,Arel::Nodes::OuterJoin)#outerfoo.join(bar,???)#left如果要生成左连接,如何连接两个表? 最佳答案 你可以使用

  3. Ruby Koans about_array_assignment - 非平行与平行分配歧视 - 2

    通过ruby​​koans.com,我在about_array_assignment.rb中遇到了这两段代码你怎么知道第一个是非并行赋值,第二个是一个变量的并行赋值?在我看来,除了命名差异之外,代码几乎完全相同。4deftest_non_parallel_assignment5names=["John","Smith"]6assert_equal["John","Smith"],names7end45deftest_parallel_assignment_with_one_variable46first_name,=["John","Smith"]47assert_equal'John

  4. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  5. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  6. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  7. ruby-on-rails - Ruby 中的内存模型 - 2

    ruby如何管理内存。例如:如果我们在执行过程中采用C程序,则以下是内存模型。类似于这个ruby如何处理内存。C:__________________|||stack|||------------------||||------------------|||||Heap|||||__________________|||data|__________________|text|__________________Ruby:? 最佳答案 Ruby中没有“内存”这样的东西。Class#allocate分配一个对象并返回该对象。这就是程序

  8. ruby - 在 Ruby 中重新分配常量时抛出异常? - 2

    我早就知道Ruby中的“常量”(即大写的变量名)不是真正常量。与其他编程语言一样,对对象的引用是唯一存储在变量/常量中的东西。(侧边栏:Ruby确实具有“卡住”引用对象不被修改的功能,据我所知,许多其他语言都没有提供这种功能。)所以这是我的问题:当您将一个值重新分配给常量时,您会收到如下警告:>>FOO='bar'=>"bar">>FOO='baz'(irb):2:warning:alreadyinitializedconstantFOO=>"baz"有没有办法强制Ruby抛出异常而不是打印警告?很难弄清楚为什么有时会发生重新分配。 最佳答案

  9. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  10. C51单片机——实现用独立按键控制LED亮灭(调用函数篇) - 2

    说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时

随机推荐