閱讀466 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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]是會報錯的。


最後更新:2017-04-03 07:57:05

  上一篇:go “寫優化”的數據結構(2):buffered tree
  下一篇:go jvm開發筆記2&#8212;java反匯編器