【问题标题】:NSMutableArray as an Instance VariableNSMutableArray 作为实例变量
【发布时间】:2011-08-18 23:15:25
【问题描述】:

我有一个实例变量,它是一个 NSMutableArray

@interface SummaryWindowController : NSWindowController {

    NSMutableArray *aBuffer;

使用此方法设置 NSMutableArray(从初始化此对象的对象调用):

- (void)setGlobalStatusArray:(NSMutableArray *)myArray
{
    if (!aBuffer) {
        [myArray retain];
        NSLog(@"aBuffer not init , alloc init now");
        aBuffer = [[NSMutableArray alloc] initWithArray:myArray];
    }
    NSLog(@"--> Received buffer: %@",aBuffer);

}

当该方法运行时,NSLog 会显示数组的内容:

2011-08-18 16:00:26.052 AppName[74751:1307] --> Recievied buffer: (
        {
        discription = DiskUsage;
        menu = "<NSMenuItem: 0x1005116e0 Hardware Status>";
        status = Warning;
    },

但在我使用此实例变量的方法中,它似乎不再被初始化

- (IBAction)refreshButtonClicked:(id)sender
{
    NSLog(@"The user has clicked the update button");
    if (!aBuffer) {
        NSLog(@"refresh button not init");
    }
    NSLog(@"Buffer is currently:%@",aBuffer);
}

当它到达这一点时,我看到以下 NSLog:

2011-08-18 16:04:25.301 AppName[74829:1307] The user has clicked the update button
2011-08-18 16:04:25.303 AppName[74829:1307] refresh button not init
2011-08-18 16:04:25.304 AppName[74829:1307] Buffer is currently:(null)

这将向我表明 aBuffer 已(自动?)释放?

任何想法为什么会这样做?起初我以为我有两个不同的对象,一个是通过从原始控制器初始化 NSWindowController 创建的:

   @interface AppName_AppDelegate : NSObject 
    NSMutableArray *globalStatusArray;

    @implementation AppName_AppDelegate

    if ( summaryWindow ) {
            [summaryWindow release];
        } // end if
        summaryWindow   = [[SummaryWindowController alloc] initWithWindowNibName:@"SummaryWindow" owner:globalStatusController];
    [summaryWindow showWindow:self];
    [summaryWindow setGlobalStatusArray:globalStatusArray];

一个在 nib 加载时创建的,相同但不同的对象,但是我现在不认为是这种情况,因为我不再看到重复的 NSLog,所以我认为它只是 NSMutableArray 的一些基本内存问题( s)?

【问题讨论】:

    标签: objective-c cocoa nsmutablearray instance-variables nswindowcontroller


    【解决方案1】:

    当你应该保留aBuffer时,你保留了myArray

    【讨论】:

    • 我只保留了 myArray,因为它是另一个问题的解决方案,我尝试同时添加 [aBuffer retain]; [myArray 保留];
    • 另外,我认为在技术上我不应该保留,因为我正在使用 initWithArray。
    【解决方案2】:

    尝试使用

    @property (nonatomic, retain) NSMutableArray *aBuffer
    

    在您的界面中。

    接下来,

     @synthesize aBuffer
    

    在您的 .m 文件中。之后,

    当你设置你的数组时,这样做:

        self.aBuffer = [[NSMutableArray alloc] initWithArray:myArray];
    

    注意“self”,以便指定属性。

    【讨论】:

    • 我已经尝试将其设为属性,不行,上面的示例只是为了确保它仍然不是 init。我想知道是否需要将 alloc/init 移动到 init 覆盖方法并使用其他一些保留的 NSMUtableArray 方法来复制数组
    猜你喜欢
    • 2020-03-22
    • 2012-03-03
    • 1970-01-01
    • 2011-08-26
    • 2011-01-06
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多