【发布时间】:2013-09-08 21:14:27
【问题描述】:
我在使用 NSMutableArray 擦除其内容时遇到问题。
考虑我的代码:(int i; 和 NSMutableArray* newFileControllerArray 一样在我的文件的 .h 中)
-(void)awakeFromNib{
i = 0;
newFileWindowControllerArray = [[NSMutableArray alloc]init];
}
-(IBAction)newFileMenubar:(id)sender{
[newFileWindowControllerArray addObject:[[NewFileWindowController alloc]initWithWindowNibName:@"NewFileWindowController"]];
NSUInteger elementsInArray = [newFileWindowControllerArray count];
NSLog(@"%lu",(unsigned long)elementsInArray);
[[newFileWindowControllerArray objectAtIndex:i] showWindow:nil];
}
-(IBAction)OKButtonClicked:(id)sender{
NSUInteger elementsInArray = [newFileWindowControllerArray count];
NSLog(@"THERE ARE %lu ELEMENTS IN THE ARRAY",(unsigned long)elementsInArray);
}
第一个调用的方法(awakeFromNib: 除外)是newFileMenubar: 这将向数组添加一个元素。我可以确认这是有效的,因为 1 打印在控制台中。但是,一旦调用 OKbutton 并打印出数组中的元素数,它就会说数组中没有元素。这是为什么呢?
我在这里遗漏了一些非常明显的东西吗?为什么我的阵列会自行重置?
编辑: cmets 变得又长又笨重,所以这里是带有 NSLogs 和输出的代码:
-(void)awakeFromNib{
i = 0;
newFileWindowControllerArray = [NSMutableArray array];
NSLog(@"self=%p, array=%p", self, newFileWindowControllerArray);
}
-(IBAction)newFileMenubar:(id)sender{
[newFileWindowControllerArray addObject:[[NewFileWindowController alloc]initWithWindowNibName:@"NewFileWindowController"]];
[[newFileWindowControllerArray objectAtIndex:i] showWindow:nil];
i++;
NSLog(@"self=%p, array=%p", self, newFileWindowControllerArray);
}
-(IBAction)OKButtonClicked:(id)sender{
NSUInteger elementsInArray = [newFileWindowControllerArray count];
NSLog(@"self=%p, array=%p", self, newFileWindowControllerArray);
[documentController newDocument:sender];
[[newFileWindowControllerArray objectAtIndex:i]close];
}
程序启动时,输出如下:self=0x100141480, array=0x100140f30 这应该来自 awakeFromNib:
下一个调用的方法是newFileMenubar:
这个的输出是
self=0x1001ac990, array=0x1005228a0 和 self=0x100141480, array=0x100140f30 之后
最后调用的方法是OKButtonClicked:
最后一个方法 (OKButtonClicked:) 的输出是 self=0x1001ac990, array=0x1005228a0
从代码中可以看出,数组的名称没有改变,但我的输出却不一样?这是什么原因造成的?
【问题讨论】:
-
也打印数组本身 (%@),确保它不为空
-
我们能看到数组的声明吗?可能的原因是它的声明方式没有保留
-
数组声明如下: NSMutableArray *newFileWindowControllerArray;在我的界面中。我正在使用 ARC
-
你确定它是你的对象在newFileMenubar和newFileMenubar中的同一个实例吗? newFileWindowControllerArray 还是同一个对象吗?或许还可以在 awakeFromNib 中添加一个 NSLog。
-
我相信数组是同一个实例。当我添加一个日志来打印数组本身时,它在 awakeFromNib 中的值为 ():在 newFileMenubar 中,该数组具有十六进制值。在 OKButton 下:它恢复为 ( )
标签: objective-c macos cocoa nsmutablearray nsarray