Objective-C: NSMutableString replaceCharactersInRange raise Exception

I expected this code to replace hatred with some love.

NSMutableString * teststring=@ "I hate programming my iPhone"; NSString * overwriteSource=@ "love"; NSRange temprange=NSMakeRange(2, 4); [teststring replaceCharactersInRange:temprange withString:overwriteSource]; NSLog(@"%@",teststring); 

This fails due to an uncaught exception, and I cannot understand why. Help! (and thanks)

+4
source share
1 answer

In your first line, you are trying to assign NSString * (@ "I hate ...") to NSMutableString * (teststring).

Your source code should give you a compilation warning:

incompatible types Objective-Initialization 'struct NSString *', expected 'structure NSMutableString *'

The following will allow your sample code to compile and work correctly:

 NSMutableString *teststring=[NSMutableString stringWithString:@"I hate programming my iPhone"]; 
+6
source

All Articles