开发者

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

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! Wh开发者_StackOverflow中文版at 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)


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.


  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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜