views:

47

answers:

2

I use an NSXMLParser to parse YouTube's API and I get all the content I want and put it into a class called Video. When I am writing to the class from inside parserDidEndElement and I end that video I write the class to an NSMutableArray. Then I NSLog the title of the video that was logged into the array. This is different for each video. I use the addObject: method to add videos to the array. However when I use parserDidEndDocument I use a for loop to read through the array and all of the entries have the same title value of the last object added! What is 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 = (the videos title)

I call this in didEndDocument:

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 added videos title for all 19 of the videos)

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

It helps if you understand the difference between a value and a reference, but that's beyond the scope of this answer. Without seeing your code, it's hard to tell what's going on, but I suspect that you're repeatedly adding (pointers to) the same video object to the array.

tc.
Yes, I have one video class that I use for all videos. How would I have different classes of video work in my app?
pki
Could I copy the object into the array and then keep using it for the parser?
pki
I have it all figured out.
pki
+2  A: 

tc's answer is correct, but let me re-phrase.

You are missing a very basic detail of Objective-C.

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

The first line declares a variable tempVideo that is a pointer to an instance of the Video class and assigns to it a reference to a freshly allocated instance of Video class.

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

What isn't shown is where and how you add the Video objects to the array.

bbum