well using NSXMLParser the values inside an array are all set to the last entry
Asked Answered
C

2

0

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)

Chessy answered 12/9, 2010 at 23:22 Comment(0)
E
3

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.

Eburnation answered 13/9, 2010 at 1:53 Comment(0)
D
1
  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.

Discountenance answered 13/9, 2010 at 0:49 Comment(2)
Yes, I have one video class that I use for all videos. How would I have different classes of video work in my app?Chessy
Could I copy the object into the array and then keep using it for the parser?Chessy

© 2022 - 2024 — McMap. All rights reserved.