jjzjj

ios - 为什么这个 Objective-C Block 会泄漏?

coder 2024-01-11 原文

我有一个棘手的 block 内存管理问题,我试图确保我理解。我正在开发一个可以播放视频的应用程序,但需要先检查用户是否真的被允许播放它。有几个步骤需要验证,其中一些需要用户交互,所以我有一大块代码看起来像这样:

MyVideoPlayer *videoPlayer = [[[MyVideoPlayer alloc] init] autorelease];
[videoPlayer canPlayAsset:(MyVideoAsset *)asset completionBlock:^(BOOL isAssetPlayable) {
    if (isAssetPlayable) {
        [videoPlayer playAsset:asset];
        [self presentModalViewController:videoPlayer animated:YES];
    }
}];

此方法可以立即返回,也可以需要一些用户输入和一些网络调用,因此是实际呈现玩家的 block 。我注意到一些奇怪的行为,我发现视频播放器被泄露了。这是我认为正在发生的事情:

  1. videoPlayer 是自动释放的。
  2. videoPlayer 由 block 保留。
  3. 该 block 执行,要么显示 videoPlayer,要么不显示。
  4. block 被释放,并释放videoPlayer
  5. videoPlayer 被解除分配(立即,如果它没有出现,或者当模态视图被关闭时)。

相反,发生的事情是这样的:

  1. videoPlayer 是自动释放的。
  2. videoPlayer 由 block 保留。
  3. 该 block 执行,要么显示 videoPlayer,要么不显示。
  4. ????

现在,我注意到如果按如下方式修改 block ,我能够获得预期的行为:

MyVideoPlayer *videoPlayer = [[[MyVideoPlayer alloc] init] autorelease];
[videoPlayer canPlayAsset:(MyVideoAsset *)asset completionBlock:^(BOOL isAssetPlayable) {
    if (isAssetPlayable) {
        [videoPlayer playAsset:asset];
        [self presentModalViewController:videoPlayer animated:YES];
    }
    [videoPlayer autorelease];
}];

但我真的不想在不知道自己在做什么的情况下添加它。

我的理解是,这不是保留循环,因为videoPlayer 既不保留也不复制该 block 。我的理解是当 block 不再在范围内时将被释放是不正确的吗?谁能帮我理解正确的方法来做到这一点?

更新

只是一些更多的信息,MyVideoPlayercanPlayAsset:completionBlock: 实现(为了保护无辜者删除了细节)看起来有点像这样:

- (void)canPlayAsset:(MyVideoAsset *)asset completionBlock:(void(^)(BOOL isAssetPlayable))completion {
    if (!asset) {
        completion(NO);
        return;
    }
    // user is a singleton object
    if (user.isGuest) {
        if ([user allowedRating:asset.rating]) {
            completion(YES);
        } else {
            // show alert
            completion(NO);
        }
    } else {
        if ([user allowedRating:asset.rating]) {
            completion(YES);
        } else {
            // prompt for pin
        }
    }
}

如您所见,我绝不会保留这个该死的 block 。 (让我们忽略 pin 部分,因为我担心它会使事情进一步复杂化。即使那部分代码不执行,问题仍然会出现。)如果 block 是一个自动释放的对象,为什么它不被释放这个函数什么时候结束执行?

更新 2

好的,我找到了。问题根本不在这个街区。正在泄露的视频播放器中有一个网络请求,其中包含一个引用了自身的 block 。

这是动画片的一部分“我今天学到了宝贵的一课......”

最佳答案

只需将第一行更改为:

__block MyVideoPlayer *videoPlayer = [[[MyVideoPlayer alloc] init] autorelease];

这样做的原因是因为:

In a reference-counted environment, by default when you reference an Objective-C object within a block, it is retained. This is true even if you simply reference an instance variable of the object. Object variables marked with the __block storage type modifier, however, are not retained.

请参阅有关 Object and Block Variables 的 Apple 文档

但为什么不一开始就发布呢?

简单的解释就是completionBlock执行后,并没有被释放。它稍后在 dealloc 中被释放,因此它保留的所有变量仍然保留。这是有道理的,因为可以根据需要多次执行 block ,直到它被释放。

我以前见过这种行为,在 block 中引用拥有 block 的对象并在 dealloc 中释放 block ,这会阻止对象被释放。 解决方案是弱引用拥有该 block 的对象。这样,拥有类型(如 MyVideoPlayer)到达 dealloc,随后释放 block (在此示例中为 completionBlock)。

使用 __block 关键字来避免保留类型的替代方法是将对象包装在 NSValue 中。通过使用 valueWithNonretainedObject:nonretainedObjectValue方法。例如:

MyVideoPlayer *videoPlayer = [[[MyVideoPlayer alloc] init] autorelease];
NSValue *videoPlayerRef = [NSValue valueWithNonretainedObject:videoPlayer];
[videoPlayer canPlayAsset:(MyVideoAsset *)asset 
          completionBlock:^(BOOL isAssetPlayable) {
              if (isAssetPlayable) {
                  MyVideoPlayer *tempVideoPlayer = 
                      (MyVideoPlayer*)[videoPlayerRef nonretainedObjectValue];
                  [tempVideoPlayer playAsset:asset];
                  [self presentModalViewController:tempVideoPlayer animated:YES];
              }
}];

编辑/对话

这部分将进一步解释为什么区 block 没有被释放。我将包括我假设 MyVideoPlayer 背后发生的事情。很高兴看到实际代码,但这应该足够了。

头文件...

typedef void(^MyVideoPlayerCompletionBlock)(BOOL isAssetPlayable);

@interface MyVideoPlayer : NSObject
@property(nonatomic, copy) MyVideoPlayerCompletionBlock completion;
... // other property definitions (or ivars)    

-(void)canPlayAsset:(MyVideoAsset*)asset 
    completionBlock:(MyVideoPlayerCompletionBlock)completion;
... // other methods defined
@end

实现...

@implementation MyVideoPlayer

@synthesize completion = _completion;

-(void)dealloc {
    // Note: Block is released in dealloc like any other property or variable
    [_completion release], _completion = nil;
    ...  // other variables and properties not shown here are released
    [super dealloc];
}

-(void)canPlayAsset:(MyVideoAsset*)asset 
    completionBlock:(MyVideoPlayerCompletionBlock)completion {
    ... // Does something with asset.  Plays it, stores it, whatever

    // Saves completion block to call at a later time.
    // Note that this code could alternatively look like
    // _completion = [completion copy];
    // Blocks are usually copied and not retained
    self.completion = completion;
}

...在某些时候,完成 block 会启动... (可能在事件处理程序或某种形式中)

-(void)SomeEventHandlerOrFuncThatCallsCompletionInMyVideoPlayer {
    // Time to call completion!
    if (self.completion) {
        self.completion(YES);  // OR no, doesn't matter
        //
        // WHOA! :: self.completion is not released
        //
        //     i.e. self.completion is not nil, and all
        //          variables inside it are still retained
        //          because calling a block doesn't also
        //          release the block.  To do that you would
        //          need to do:     self.completion = nil;
        //          AFTER calling:  self.completion(...);
        //
        //    SO...
        //
        //          Because the block was not released, it is
        //          still retaining variables (such as the current
        //          instance of MyViewPlayer).  Note that the
        //          Block will never be released until dealloc
        //          is called.  :(  So..., if you want the block
        //          to retain the current MyViewPlayer until
        //          execution of the completion block is over, you
        //          will want to call:  self.completion = nil;
        //          to release the block and all associated variables
        //          after calling the completion block.
    }
}

@end

关于ios - 为什么这个 Objective-C Block 会泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9490905/

有关ios - 为什么这个 Objective-C Block 会泄漏?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类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

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

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

  3. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  4. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  5. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用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

  6. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  7. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  8. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  9. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  10. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

随机推荐