/core/externals/google-toolbox-for-mac/Foundation/GTMNSString+Replace.m

http://macfuse.googlecode.com/ · Objective C · 53 lines · 18 code · 9 blank · 26 comment · 2 complexity · 559a1818976c6a63099fc17541d4b0ed MD5 · raw file

  1. //
  2. // GTMNSString+Replace.m
  3. //
  4. // Copyright 2006-2008 Google Inc.
  5. //
  6. // Licensed under the Apache License, Version 2.0 (the "License"); you may not
  7. // use this file except in compliance with the License. You may obtain a copy
  8. // of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  14. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  15. // License for the specific language governing permissions and limitations under
  16. // the License.
  17. //
  18. #import "GTMNSString+Replace.h"
  19. @implementation NSString (GTMStringReplaceAdditions)
  20. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  21. // 10.5 has stringByReplacingOccurrencesOfString:withString:, use that directly.
  22. - (NSString *)gtm_stringByReplacingString:(NSString *)target
  23. withString:(NSString *)replacement {
  24. // If |target| was nil, then do nothing and return |self|
  25. //
  26. // We do the retain+autorelease dance here because of this use case:
  27. // NSString *s1 = [[NSString alloc] init...];
  28. // NSString *s2 = [s1 stringByReplacingString:@"foo" withString:@"bar"];
  29. // [s1 release]; // |s2| still needs to be valid after this line
  30. if (!target)
  31. return [[self retain] autorelease];
  32. // If |replacement| is nil we want it to be treated as if @"" was specified
  33. // ... effectively removing |target| from self
  34. if (!replacement)
  35. replacement = @"";
  36. NSMutableString *result = [[self mutableCopy] autorelease];
  37. [result replaceOccurrencesOfString:target
  38. withString:replacement
  39. options:0
  40. range:NSMakeRange(0, [result length])];
  41. return result;
  42. }
  43. #endif // MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  44. @end