捷径系列:NSString

来源:互联网 发布:报纸版面编辑软件 编辑:程序博客网 时间:2024/05/01 04:43

 

该系列文章来自http://borkware.com/quickies/。无论是学习还是开发都可以从这里获得很多有用的代码段,从而省去了很多调查和搜索的时间。

1 合并一个字符串数组到单个字符串。

  1. NSArray *chunks  = ... get an array, say by splitting it;  
  2. string = [chunks componentsJoinedByString: @" :-) "]; 

输出结果如下:

  1. oop :-) ack :-) bork :-) greeble :-) ponies 

2 将一个字符串分割成数组

  1. NSString *string = @"oop:ack:bork:greeble:ponies";  
  2. NSArray *chunks = [string componentsSeparatedByString: @":"]; 

3 将字符串转换成整型数

  1. NSString *string = ...;  
  2. int value = [string intValue]; 

同样NSString也有floatValue和doubleValue的方法。

4 遍历属性字符串(Attributed string)中的属性
如下函数可以打印出输入的属性字符串中的所有属性

  1. - (void) iterateAttributesForString: (NSAttributedString *) string  
  2. {  
  3.     NSDictionary *attributeDict;  
  4.     NSRange effectiveRange = { 0, 0 };  
  5.     do {  
  6.         NSRange range;  
  7.         range = NSMakeRange (NSMaxRange(effectiveRange),  
  8.                              [string length] - NSMaxRange(effectiveRange));  
  9.         attributeDict = [string attributesAtIndex: range.location  
  10.                                 longestEffectiveRange: &effectiveRange  
  11.                                 inRange: range];  
  12.         NSLog (@"Range: %@  Attributes: %@",  
  13.                NSStringFromRange(effectiveRange), attributeDict);  
  14.     } while (NSMaxRange(effectiveRange) < [string length]);  

5 制作本地化的字符串
你需要在English.lproj目录(或其他合适的本地化目录)中有一个名为Localizable.strings的文件。它有如下的语法: 

  1. "BorkDown" = "BorkDown";  
  2. "Start Timer" = "Start Timer";  
  3. "Stop Timer" = "Stop Timer"; 

也就是,每个键值都有一个本地化的值。

在代码中,可以使用NSLocalizedString()或其变种。

  1. [statusItem setTitle: NSLocalizedString(@"BorkDown", nil)]; 

其中该函数忽略了第二个参数。

6 无多余信息的NSLog
NSlog在日志行之前输出了太多无关信息。对于一个用于输出的基础工具,它确实有点碍事。不过我仍然和喜欢printf()系列所不能的%@展开替换。如下是可以实现该功能的代码:

  1. #include <stdarg.h> 
  2. void LogIt (NSString *format, ...)  
  3. {  
  4.     va_list args;  
  5.     va_start (args, format);  
  6.     NSString *string;  
  7.     string = [[NSString alloc] initWithFormat: format  arguments: args];  
  8.     va_end (args);  
  9.     printf ("%s/n", [string cString]);  
  10.     [string release];  

7 在属性字符串中加入图片
我们需要使用一个文本附件:

  1. - (NSAttributedString *) prettyName  
  2. {  
  3.     NSTextAttachment *attachment;  
  4.     attachment = [[[NSTextAttachment alloc] init] autorelease];  
  5.     NSCell *cell = [attachment attachmentCell];  
  6.     NSImage *icon = [self icon]; // or wherever you are getting your image  
  7.     [cell setImage: icon];  
  8.     NSString *name = [self name];  
  9.     NSAttributedString *attrname;  
  10.     attrname = [[NSAttributedString alloc] initWithString: name];  
  11.     NSMutableAttributedString *prettyName;  
  12.     prettyName = (id)[NSMutableAttributedString attributedStringWithAttachment:  
  13.                                                 attachment]; // cast to quiet compiler warning  
  14.     [prettyName appendAttributedString: attrname];  
  15.     return (prettyName);  
  16. }  

这样就可以在字符串前面加入图片。如果需要在字符串中加入图片就需要创建通过附件创建一个属性字符串,然后将其加入到最终的属性字符串中。

8 除去字符串中的换行符
假定有一个字符串,你想除去换行符。你可以像脚本语言一样进行一个分割/合并操作,或者制作一个可变的拷贝并进行处理:

  1. NSMutableString *mstring = [NSMutableString stringWithString:string];  
  2. NSRange wholeShebang = NSMakeRange(0, [mstring length]);  
  3. [mstring replaceOccurrencesOfString: @"  
  4.  
  5.          withString: @""  
  6.          options: 0  
  7.          range: wholeShebang];  
  8. return [NSString stringWithString: mstring]; 

(这也可用于通用的字符串操作,不仅经是除去换行符)
该方法比分割/合并至少省一半的时间。当然可能结果不会造成太多的不同。在一个简单的测试中,处理一个1.5兆文件中36909个新行,分割/合并操作花费了0.124秒,而上述方法仅需0.071秒。

9 字串匹配

  1. NSRange range = [[string name] rangeOfString: otherString options: NSCaseInsensitiveSearch]; 

10 今天日期的字符串
将一个日期转换成字符串的通用方法就是通过NSDateFormatter。有时你想生成一个格式比较友好的日期字符串。比如你需要"December 4, 2007",这种情况下就可以使用:

  1. [[NSDate date] descriptionWithCalendarFormat: @"%B %e, %Y" timeZone: nil locale: nil] 

(感谢Mike Morton提供该方法)

11 除去字符串末尾的空格

  1. NSString *ook = @"/n /t/t hello there /t/n  /n/n";  
  2. NSString *trimmed =  
  3.  [ook stringByTrimmingCharactersInSet:  
  4.  [NSCharacterSet whitespaceAndNewlineCharacterSet]];  
  5. NSLog(@"trimmed: '%@'", trimmed); 

输出结果是:
    2009-12-24 18:24:42.431 trim[6799:903] trimmed: 'hello there'

图形
1 绘制一个粗体字符串

  1. - (void) drawLabel: (NSString *) label  
  2.            atPoint: (NSPoint) point  
  3.               bold: (BOOL) bold {  
  4.     NSMutableDictionary *attributes = [NSMutableDictionary dictionary];  
  5.     NSFont *currentFont = [NSFont userFontOfSize: 14.0];  
  6.     if (bold) {  
  7.  NSFontManager *fm = [NSFontManager sharedFontManager];  
  8.  NSFont *boldFont = [fm convertFont: currentFont  
  9.                                toHaveTrait: NSBoldFontMask];  
  10.  [attributes setObject: boldFont  
  11.                     forKey: NSFontAttributeName];  
  12.     } else {  
  13.  [attributes setObject: currentFont  
  14.                     forKey: NSFontAttributeName];  
  15.     }  
  16.     [label drawAtPoint: point  withAttributes: attributes];;  

原创粉丝点击