I have an Model Class. When I call a the method “setter”, I set some String values to the attributes of my object. After the attributes are set, the method returns the new Object which is stored in the NSMutableArray *eintraegeSortiert.
Now, I need a new Object. I think I have to remove the pointer and set it again. If I don’t remove the pointer, all the objects stored in the mutable array will change too and I have stored the same object a 100 times in that mutable array. I have tried in multiple ways, without getting it right. What am I doing wrong? My code:
NSMutableArray *eintraegeSortiert = [NSMutableArray array];
for (int i = 0; i < ([mArray count] / 11) ; i++) {
Vertretung *vertretung = [[Vertretung alloc] init];
[eintraegeSortiert addObject:[self setter:mArray :vertretung]];
}
I think you’re not really understanding how the code you’ve written works. Let’s take a look at it:
So step by step:
Creates a new mutable array and assigns it to
eintraegeSortiertWe’re going to loop
[mArray count] / 11times.Now, this is creating a variable within the current scope called
vertretung. You callalloc/init. That will return a pointer to a newVertretungobject. For example this might be at memory location0x12345678. Then you add that to the array.Then we get to the end of the current scope and loop back around the for-loop. That means the variable
vertretunggoes out of scope.Then when you loop around again, that same code runs again and again. But now the
alloc/initwill create an entirely newVertretungobject (maybe pointing to memory location0xabcdef00and add that to the array.So no, it’s not the same object being added to the array multiple times.
Not sure what’s going on in
setter::– maybe post that as well if you’re still having issues.