NSMutableString stringByReplacingOccurrencesOfString Warning
I've got an RSS parser method a开发者_如何学编程nd 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?
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];
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]];
That usually means you dropped the asterisks in the definition of (in this case) currentSummary.
So you most likely have:
NSMutableString currentSummary;
when you need:
NSMutableString *currentSummary;
In the first case, since Objective-C classes are defined in type structures, the complier thinks your trying to assign a NSString to a struct.
I make this typo on a distressingly regular basis.
精彩评论