htmliosobjective-cstringnsscanner

stringByReplacingOccurrencesOfString not functioning correctly


I created a small app which will get html from website and turn that into string. Now I want to delete some text from that string but it is not deleting that text. Here is my code that I wrote.

-(void)dk {
    NSString *myURLString = @"http://bountyboulevardss.eq.edu.au/?cat=3&feed=rss2";
    NSURL *myURL = [NSURL URLWithString:myURLString];

    NSError *error = nil;
    NSString *myHTMLString = [NSString stringWithContentsOfURL:myURL encoding: NSUTF8StringEncoding error:&error];

    [myHTMLString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];


    if (error != nil)
    {
        NSLog(@"Error : %@", error);
    }
    else
    {

    }

    [myHTMLString stringByReplacingOccurrencesOfString:@"<title>Bounty Boulevard &#187; &#187; Latest News</title>" withString:@""];

    NSString *newString = myHTMLString;


    NSScanner *scanner = [NSScanner scannerWithString:newString];
    NSString *token = nil;
    [scanner scanUpToString:@"<title>" intoString:NULL];
    [scanner scanUpToString:@"</title>" intoString:&token];

    headline.text = token;

    NSLog(@"%@", myHTMLString);




}

Like you see in the beginning I try to delete the first title in the text and then I scan for the title I still keep getting the title I deleted. I checked in log and it is not deleting. I don't know what I am doing wrong. Sorry guys if this is really easy. Thanks for helping.


Solution

  • Not an Objective-C expert myself, but I guess you need to assign the replaced value back to the variable:

    myHTMLString = [myHTMLString stringByReplacingOccurrencesOfString:@"<title>Bounty Boulevard &#187; &#187; Latest News</title>" withString:@""];
    

    So, in general the idiomatic way to replace a string and keeping the result in the same variable is:

    str = [str stringByReplacingOccurrencesOfString....];
    

    This is confirmed by the stringByReplacingOccurencesOfString doc which states that this method "returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.".