NSMutableArray is empty after addObject

为君一笑 提交于 2019-11-30 15:17:19

问题


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]);

This is the output:

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

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.

Anybody a guess?


回答1:


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];

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.




回答2:


Your NSMutableArray is indeed almost certainly null. It won't raise an exception, because sending any message to nil in ObjC is a no-op and would behave as you're seeing, with a return value of zero or nil, etc.

Try logging that as well to double check.



来源:https://stackoverflow.com/questions/12282808/nsmutablearray-is-empty-after-addobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!