'尝试使用appendString改变不可变对象:'解析xml时出错

时间:2015-01-21 22:10:47

标签: ios rss nsmutablestring nsxml

我使用NSXMLParser在Objective-C中解析rss feed。 这个rss类似于:

<?xml version="1.0" encoding="UTF-8"?>
                <rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
                    <channel>
                        <title>My RSS</title>
                        <description>My Rss parser</description>

                <item>

                <title>Some kind of a title</title>
                <description>
                <![CDATA[]]>
                </description>
                <media:thumbnail url="http://www.example.org/pics/Thumbs/picture.jpg"/>
                <pubDate>Tue, 20 Jan 2015 22:24:56 -0500</pubDate>
            </item>
</channel>
                </rss>

我的NSXML代表就是这样:

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {


    element = elementName;

    if ([element isEqualToString:@"item"]) {

        item    = [[NSMutableDictionary alloc] init];
        title   = [[NSMutableString alloc] init];
        pubDate = [[NSMutableString alloc] init];

    }

    if([element isEqualToString:@"media"]){
        imageLink = [[NSMutableString alloc] init];
      imageLink = [attributeDict objectForKey:@"url"];
    }

    NSLog (@"Parse did Start");
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

    if ([element isEqualToString:@"title"]) {
        [title appendString:string];
    } else if ([element isEqualToString:@"media"]) {
        imageLink = string;
    } else if ([element isEqualToString:@"pubDate"]) {
        [pubDate appendString:string];
    }
    NSLog(@"Found characters");
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if ([elementName isEqualToString:@"item"]) {

        [item setObject:title forKey:@"title"];
       [item setObject:imageLink forKey:@"media"];
        [item setObject:pubDate forKey:@"pubDate"];

        [feeds addObject:[item copy]];

    }

    NSLog(@"Did end elements");

}

- (void)parserDidEndDocument:(NSXMLParser *)parser {

    [self.tableView reloadData];
    NSLog(@"Parsing is done");
    NSLog(@"%@", title);

}

我已经宣布了所有需要的变量。正如您可能已经看到的那样,我试图解析以rss元素的属性形式呈现的链接。在我这样做之前,应用程序运行正常,但是图像imageLink = [attributeDict objectForKey:@"url"];&#34;尝试使用appendString改变不可变对象:&#34; bug出现了。

你觉得怎么样?

1 个答案:

答案 0 :(得分:2)

当您使用NSMutableString时,您应该替换以下代码

if([element isEqualToString:@"media"]){
    imageLink = [[NSMutableString alloc] init];
    imageLink = [attributeDict objectForKey:@"url"];
   }

 if([element isEqualToString:@"media"]){
       imageLink = [[NSMutableString alloc] init];
      [imageLink appendString:[attributeDict objectForKey:@"url"]];
    }