addObject后NSMutableArray

addObject后NSMutableArray

本文介绍了addObject后NSMutableArray为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个对象添加到NSMutableArray中:

I want to add an object into an NSMutableArray:

NSLog(@"Object text: %@", object.text);
NSLog(@"Object: %@", object);
[appdelegate.objects addObject:object];
NSLog(@"Objects array size: %i", [appdelegate.objects count]);

这是输出:

Object text: This is the text
Object: <Object: 0x6e762c0>
Objects array size: 0

这是怎么可能的,我添加了一个对象,下一行,它仍然是空的。 NSMutableArray 不是 nil ,因为这会引发异常。

How is this possible, I add an object, on the next line, it is still empty. The NSMutableArray is not nil, because that would raise an exception.

有人在猜吗?

推荐答案

如果它是 nil,它不会引发异常。如果它通常响应该消息,您仍然可以发送 nil 对象。在这种情况下,你只会得到0.我认为你没有分配数组。确保你这样做:

It would not raise an exception if it was nil. You can still message a nil object if it usually responds to that message. In this case, you'll just get 0. I think you're not allocating the array. Make sure you're doing this:

array = [[NSMutableArray alloc] init];

作为调试提示,如果您不确定对象的状态并想确定该对象确实存在并且可以使用,请使用 assert(appdelegate.objects); 如果数组为nil,则代码将停止在此行执行。如果它没有在此行停止,那么您就知道该对象存在于内存中。

As a debugging tip, if you're unsure about the state of an object and want to make sure the object indeed exists and is ready to be used, use assert(appdelegate.objects); If the array is nil, your code will stop executing at this line. If it doesn't stop at this line, then you know the object exists in memory.

这篇关于addObject后NSMutableArray为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 08:58