Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableString stringByReplacingOccurrencesOfString Warning

I've got an RSS parser method and I need to remove whitespace and other nonsense from my extracted html summary. I've got a NSMutableString type 'currentSummary'. When I call:

currentSummary = [currentSummary 
        stringByReplacingOccurrencesOfString:@"\n" withString:@""];

Xcode tells me "warning: assignment from distinct Objective-C type"

What's wrong with this?

like image 833
quantum Avatar asked Oct 30 '09 00:10

quantum


2 Answers

If currentSummary is already a NSMutableString you shouldn't attempt to assign a regular NSString (the result of stringByReplacingOccurrencesOfString:withString:) to it.

Instead use the mutable equivalent replaceOccurrencesOfString:withString:options:range:, or add a call to mutableCopy before the assignment:

// Either
[currentSummary replaceOccurencesOfString:@"\n" 
                               withString:@"" 
                                  options:NULL
                                    range:NSMakeRange(0, [receiver length])];

// Or
currentSummary = [[currentSummary stringByReplacingOccurrencesOfString:@"\n"
                                                            withString:@""]
                  mutableCopy];
like image 101
Tim Avatar answered Oct 09 '22 01:10

Tim


This works great for nested elements as well of course:

*Edited*

// Get the JSON feed from site
myRawJson = [[NSString alloc] initWithContentsOfURL:[NSURL 
            URLWithString:@"http://yoursite.com/mobile_list.json"] 
            encoding:NSUTF8StringEncoding error:nil];

// Make the content something we can use in fast enumeration
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary * myParsedJson = [parser objectWithString:myRawJson error:NULL];
[myRawJson release];
allLetterContents = [myParsedJson objectForKey:@"nodes"];

    // Create arrays just for the title and Nid items
    self.contentTitleArray = [[NSMutableArray alloc]init];

    for (NSMutableDictionary * key in myArr) {
        NSDictionary *node = [key objectForKey:@"node"];
        NSMutableString *savedContentTitle = [node objectForKey:@"title"];        

        // Add each Title and Nid to specific arrays
        //[self.contentTitleArray addObject:contentTitle];

        //change each item with & to &
        [self.contentTitleArray addObject:[[savedContentTitle      
                                stringByReplacingOccurrencesOfString:@"&" 
                                withString:@"&"] 
                                mutableCopy]];

    }

The code below, as shown in the use-case above might be helpful.

[self.contentTitleArray addObject:[[contentTitle 
                                    stringByReplacingOccurrencesOfString:@"&" 
                                    withString:@"&"] 
                                    mutableCopy]];
like image 20
Pat Avatar answered Oct 09 '22 01:10

Pat