问题
I think, I am doing a pretty basic mistake, but I am using an NSMutableArray
and this somehow doesn't add the object, I'm sending it its way. I have a property (and synthesize)
@property (nonatomic, strong) NSMutableArray *kpiStorage;
and then:
ExampleObject *obj1 = [[ExampleObject alloc] init];
[kpiStorage addObject:obj1];
ExampleObject *obj2 = [[ExampleObject alloc] init];
[kpiStorage addObject:obj2];
NSLog(@"kpistorage has:%@", [kpiStorage count]);
and that always returns (null) in the console. What am I misunderstanding?
回答1:
Make sure you allocated memory for kpiStorage.
self.kpiStorage = [[NSMutableArray alloc] init];
回答2:
On top of forgetting to allocated memory for your NSMutableArray, your NSLog formatting is also wrong. Your app will crash when you run it. The following changes are needed
You will need to add
self.kpiStorage = [[NSMutableArray alloc] init];
and change your NSLog to the following
NSLog(@"kpistorage has:%d", [self.kpiStorage count]);
回答3:
If you are not using ARC make sure you should not create a memory leak in your project. So better way would be allocating like this
NSMutableArray *array = [[NSMutableArray alloc] init];
self.kpiStorage = array;
[array release];
make it a habit to do not directly do
self.kpiStorage = [[NSMutableArray alloc] init];
in this case your property's retain count is incremented by 2. For further reading you can stydy Memory Leak when retaining property
来源:https://stackoverflow.com/questions/15042870/nsmutablearray-does-not-add-objects