Using NSXMLParser, the values โ€‹โ€‹inside the array are set to the last record

I use NSXMLParser to parse the YouTube APIs and I get all the content I want and put it in a class called "Video". When I write to a class from parserDidEndElement and I end this video, I write a class in NSMutableArray . Then I NSLog the name of the video that was recorded in the array. This is different for each video. I use the addObject: method to add video to an array. However, when I use parserDidEndDocument , I use a for loop to read through the array, and all records have the same name value of the last added object! What's going on here?

I call this in didEndElement:

Video *tempVideo = [Video new]; NSString *title = @""; tempVideo = [allVideos objectAtIndex:[allVideos count]-1]; title = tempVideo.videoTitle; NSLog(@"1videoTitle = %@", title); 

It returns for each element 1videotitle = (video title)

I call this in the didEndDocument file:

 int i; Video *tempVideo = [Video new]; NSString *title = @""; for(i=0;i<[allVideos count];i++){ tempVideo = [allVideos objectAtIndex:i]; title = tempVideo.videoTitle; NSLog(@"videoTitle = %@", title); } 

It returns for each element videotitle = (the last video title added for all 19 videos)

0
iphone youtube-api nsmutablearray nsxmlparser
source share
2 answers

tc answer is correct, but let me rephrase.

You are missing an elementary part of Objective-C.

 Video *tempVideo = [Video new]; tempVideo = [allVideos objectAtIndex:[allVideos count]-1]; 

The first line declares the variable tempVideo , which is a pointer to an instance of the Video class and assigns it a link to the newly selected instance of the Video class.

The second line reassigns tempVideo as a reference to an object from the allVideos array. This is not a copy of the object, but a reference to the same object in the array. The first instance - one of [Video new] - effectively leaked.

What is not shown, where and how you add Video objects to the array.

+3
source share
  • Video * tempVideo defines a variable called "tempVideo", which is a pointer to the video.
  • [Video new] creates a new video.
  • tempVideo = [allVideos objectAtIndex:[allVideos count]-1]; overwrites your pointer (video leak created in step 2).

This helps if you understand the difference between a value and a link, but it is beyond the scope of this answer. Without seeing your code, it's hard to say what is happening, but I suspect that you repeatedly add (point to) the same video object to the array.

+1
source share

All Articles