NSMutableArray is empty after addObject

2019-02-09 12:52发布

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?

2条回答
▲ chillily
2楼-- · 2019-02-09 13:21

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.

查看更多
看我几分像从前
3楼-- · 2019-02-09 13:22

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.

查看更多
登录 后发表回答