NSMutableArray does not add objects [duplicate]

天大地大妈咪最大 提交于 2020-02-22 06:48:06

问题


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

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