NSString中的stringByReplacingOccurrencesOfString

今天学习iOS开发中,关于textfield和textview的相关内容,其实也就是按照SAM ios6 application development 第7章中介绍的例子在编写了。其中程序的作用是可以读取textfield中的内容然后替换掉textview中标记出来的地方。

程序最后3行:

       self.theStory.text = [self.theTemplate.text
                          stringByReplacingOccurrencesOfString:@"<place>" withString:self.thePlace.text];
    NSLog(@"theStory:%@",self.theStory.text);
    self.theStory.text = [self.theStory.text
                          stringByReplacingOccurrencesOfString:@"<verb>" withString:self.theVerb.text];

    self.theStory.text = [self.theStory.text
                          stringByReplacingOccurrencesOfString:@"<number>" withString:self.theNumber.text];

刚开始的时候,我没有注意,将后两个语句中theStory写成了theTemplate,结果最后运行得到的结果都只是把<number>替换掉了,前两处标记都没有替换,当时没有仔细看,觉得很费解,后来就用NSLog 查看theStory text的变化,发现果然如果是替换theTemplate的text内容,得到的theStory中的内容都是分开的,也就是并没有改变theTemplate的内容。后来有翻阅了一下资料,查看了下stringByReplacingOccurrencesOfString的相关资料:

关于该函数的Description:

Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.

函数returns:

A new string in which all occurrences of target in the receiver are replaced by replacement.

也就是说调用该函数后,原来的对象并没有发生变化,而是返回一个新的对象,所以如果每次都是对template中的text进行替换,当然相当于只进行了最后一个函数,对number的替换。

后来偶然翻到了别人研究这个函数发现的问题,还看到这个函数得到的新对象是autorelease属性的,不需要手动对其release:

NSString * s = [[NSString alloc] initWithFormat:@"1s"];
    s = [s stringByReplacingOccurrencesOfString:@"s" withString:@"x"];
    NSLog(@"%@",s);
    [s release];

代码最后的[s release]是会报错的。


上一篇:如何在高版本的Xcode中部署低版本的ios程序


下一篇:《iOS6 application development》学习之路:No.2