简体   繁体   中英

NSMutableArray is empty after addObject

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM