【问题标题】:Failing to Release after Multiple Nib loads多次加载笔尖后无法释放
【发布时间】:2011-05-11 18:08:47
【问题描述】:

我使用 Nib 作为几个按钮的模板。它似乎工作正常,他们每个人都有自己独立的状态。但是,当我去释放按钮时,我会在 dealloc 中崩溃。这是代码...

mSoundBtns = new cSoundButton*[mNumSounds];
for(unsigned int i = 0 ; i < mNumSounds; ++i) {
    mSoundBtns[i] = nil;
}

for(unsigned int s = 0; s < mNumSounds; ++s) {

    [[NSBundle mainBundle] loadNibNamed:@"InstanceSoundButton" owner:self options:nil];
    //Auto Loads via Outlet into 'soundNib'

    mSoundBtns[s] = soundNib;
    soundNib = nil;

    uint32 count = mSoundBtns[s].retainCount;
    NSLog(@"Last Count: %d", count);
}


for(unsigned int j = 0; j < mNumSounds; ++j) {
    [mSoundBtns[j] release];  //**** Crash here on 7th (of 8) release
    mSoundBtns[j] = nil;
}

标题:

@interface cLocationContext {
   ...

   cSoundButton** mSoundBtns;
   IBOutlet cSoundButton* soundNib;

}

@property (nonatomic, assign) IBOutlet cSoundButton* soundNib;

@end

Nib 非常简单,它只包含一个自定义视图类型的父视图和一个子视图。

cSoundButton 只跟踪名称和布尔状态 Mute or Not。这是dealloc

- (void)dealloc {

    delete[] mSoundTag;

    // Call the inherited implementation
    [super dealloc];  //****Crashes in here
}

崩溃发生在对 super dealloc 的调用中,在 UIButton -> UIButtonContent dealloc 中。我假设我的内存管理做得很差,比如释放两次,但我不知道在哪里。

我多次加载笔尖的做法合法吗?

【问题讨论】:

  • retainCount 没用。不要叫它。

标签: iphone objective-c memory-management refcounting


【解决方案1】:

从NIB 加载按钮后,您必须保留该按钮。如果不这样做,则不允许您稍后释放它,并且一旦您的代码将控制权返回给运行循环(当自动释放池耗尽时),您将无法访问该按钮。

PS:使用 Cocoa 集合 (NSMutableArray) 来存储对按钮的引用不是更容易吗?你的代码在我看来太复杂了。

【讨论】:

    【解决方案2】:

    如果您使用您的属性并使用NSArray 来存储按钮实例,这将大大简化您的内存管理。

    [[NSBundle mainBundle] loadNibNamed:@"InstanceSoundButton" owner:self options:nil];
    //Auto Loads via Outlet into 'soundNib'
    
    [mSoundBtns addObject:self.soundNib];
    self.soundNib = nil;
    

    等到发布的时候

    [mSoundBtns release];
    

    请记住,当您使用属性时,您必须通过self 引用它们。以下两行完全等价:

    self.soundNib = something;
    [self setSoundNib:something];
    

    当您设置soundNib = nil 时,您将变量soundNib 设置为空,失去对您加载的按钮的引用。如果您没有将指针添加到数组并稍后释放它,那么您将泄漏所有内容。从技术上讲,你这样做的方式可能会奏效......但不要那样做。使用正确的NSArrays 和属性将使整个过程变得更容易和更易于维护。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 2016-11-30
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多