Reputation: 1395
I am experiencing unexpected behavior when adding objects to an NSMutablearray. Basically, i want to add an object at the end of the array. All the objects in the array should be different. But what I am seeing is that all the objects in the array equal to the last one that was inserted. I have included the relevant code:
_trafficArray = [[NSMutableArray alloc] init];
int _index = -1;
int _currentIndex = 0;
int _reportCount = 0;
TrafficReport *_report = [[TrafficReport alloc] init];
while (true) {
if (!xmlTextReaderRead(_reader)) break;
switch (xmlTextReaderNodeType(_reader)) {
case XML_READER_TYPE_ELEMENT:
temp = (char *)xmlTextReaderConstName(_reader);
currentTagName = [NSString stringWithCString:temp encoding: NSUTF8StringEncoding];
if([currentTagName isEqualToString:@"Title"])
{
_index++;
temp = (char *)xmlTextReaderConstName(_reader);
currentTagName = [NSString stringWithCString:temp encoding: NSUTF8StringEncoding];
xmlTextReaderRead(_reader);
temp = (char*)xmlTextReaderConstValue(_reader);
currentTagValue = [NSString stringWithCString:temp
encoding:NSUTF8StringEncoding];
_report.title = currentTagValue;
_reportCount++;
}
if ([currentTagName isEqualToString:@"Description"]) {
temp = (char *)xmlTextReaderConstName(_reader);
currentTagName = [NSString stringWithCString:temp encoding: NSUTF8StringEncoding];
xmlTextReaderRead(_reader);
temp = (char*)xmlTextReaderConstValue(_reader);
currentTagValue = [NSString stringWithCString:temp
encoding:NSUTF8StringEncoding];
_report.description = currentTagValue;
_reportCount++;
}
if (_reportCount==2) {
_reportCount = 0;
NSLog(@"updated! with index = %d and title = %@\n\n", _index, _report.title);
[_trafficArray insertObject:_report atIndex:_index];
[_report release];
TrafficReport *_report = [[TrafficReport alloc] init];
}
continue;
default:continue;
}
}
Upvotes: 0
Views: 282
Reputation: 53551
It's an issue of scope. After you release _report
, you declare a new _report
object in the scope of the if statement. Even though it has the same name as the one you declared before the while loop, it refers to a different variable. Remove the declaration (TrafficReport *
) before the assignment to assign a new value to your existing _report
variable instead.
Upvotes: 2