为什么我的NSMutableArray返回nill?

lam*_*ade 1 cocoa

我有一个非常简单的任务:将textField的内容添加到NSMutableArray.问题是数组返回nill.我相信这与我正在使用的数组被声明为实例变量这一事实有关.

/*
 IBOutlet NSTextField *textField;
 IBOutlet NSTabView *tableView;
 IBOutlet NSButton *button;
 NSMutableArray *myArray;
 */

#import "AppController.h"


@implementation AppController


-(IBAction)addNewItem:(id)sender
{
    NSString *string = [textField stringValue];
    NSLog(@"%@",string);

    [myArray addObject:string];
    NSLog(@"%d",[myArray count]);//this outputs 0 why is that?

}
Run Code Online (Sandbox Code Playgroud)

its*_*att 6

你在某处做过以下的事吗?

myArray = [[NSMutableArray alloc] init];
Run Code Online (Sandbox Code Playgroud)

如果你不做那样的事情,myArray只是一个空指针,而addObject调用只会默默地做什么.


编辑:这里的想法是,如果你只有一个指针变量,则没有创建NSMutableArray对象.在调用allocinit之前,没有对象.

查看此CocoaDev页面,了解有关NSMutableArray及其用途的更多信息.而苹果公司的文档对的NSMutableArray方法的信息.


而且,这与这个问题基本上是同一个问题.