问题
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