我是 iphone 开发的菜鸟,我正在尝试从 NSString 值创建一个子字符串,该值总是会改变。基本上,我正在尝试对字符串的最后一部分进行子串化。该字符串的格式为“March 15 PM Metals Commentary: John Jones” 我想要字符串的姓氏部分 例如,“Jones”而不是“John Jones”。我尝试过的两种方法要么给我异常,要么不返回任何值。任何帮助是极大的赞赏。
我的代码
//This approach throw index out of bounds exception
NSString * storyLink2 = [[stories objectAtIndex: storyIndex] objectForKey: @"title"];
NSRange namestart = [storyLink2 rangeOfString:@" " options:NSBackwardsSearch];
NSString *name = [[[stories objectAtIndex: storyIndex] objectForKey: @"title"] substringWithRange:NSMakeRange(namestart.location +1, name.length - namestart.location+1)];
//This approach return nothing
NSString *name = [[stories objectAtIndex: storyIndex] objectForKey: @"title"];
NSArray *thingitems = [name componentsSeparatedByString:@" "];
name = [thingitems lastObject];
编辑
NSString *name = [[stories objectAtIndex: storyIndex] objectForKey: @"title"];
NSLog(@"myname: %@", name);// <-- Showing "March 15 PM Metals Commentary: John Jones"
NSArray *thingitems = [name componentsSeparatedByString:@":"]; ////<-- [__NSArrayM componentsSeparatedByString:]: unrecognized selector sent to instance 0x89741a0
NSArray *lastName=[thingitems componentsSeparatedByString:@" "];
name = [lastName lastObject];
NSLog(@"myname: %@", name);
日志
2013-03-17 01:30:39.738 GSCC[704:207] myname: March 15 PM Metals Commentary: Thomas Vitiello
2013-03-17 01:30:39.739 GSCC[704:207] -[__NSArrayM componentsSeparatedByString:]: unrecognized selector sent to instance 0x89741a0
2013-03-17 01:30:39.741 GSCC[704:207] Exception - -[__NSArrayM componentsSeparatedByString:]: unrecognized selector sent to instance 0x89741a0