【问题标题】:Help with string manipulation method字符串操作方法的帮助
【发布时间】:2011-04-16 16:12:38
【问题描述】:

我有一个名为 getTitle 的方法,它属于 NSString 类别,它会删除字符串 "(" 和 ")" 之间的任何内容,并且还会删除这些字符串。但是,当输入字符串不包含上述任何一个字符串时,该方法将崩溃并报错:

* 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“* -[NSArray objectAtIndex:]: index 1 beyond bounds [0 .. 0]”

这是由于 NSArray 'a' 没有对象造成的。

但是,我似乎无法修复它。请您看看下面的代码并指出问题所在吗?

- (NSString *)getTitle {
    NSArray *a = [self componentsSeparatedByString:@"("];
    if ([a count] > 0) {
        if ([a objectAtIndex:1] != [NSNull null])  {
        NSString *b = [a objectAtIndex:1];
        NSArray *c = [b componentsSeparatedByString:@")"];
        if ([c count] == 0)
            return self;
        if ([a objectAtIndex:0] != nil && [c objectAtIndex:1] !=nil)
            return [[[a objectAtIndex:0] stringByAppendingString:[c objectAtIndex:1]] stringByReplacingOccurrencesOfString:@"  -" withString:@" -"];
        else 
            return self;
        }
            else
                return self;
    }
    else {
        return self;
    }
    return self;
}

【问题讨论】:

  • 仅供参考:编译器理解长度超过一个字符的变量名

标签: objective-c xcode ios4 string nsarray


【解决方案1】:

这行可能会崩溃:

if ([a objectAtIndex:1] != [NSNull null])  {

我猜您正在尝试检查componentsSeparatedByString: 是否返回了一个包含多个组件的数组。正确的方法是检查if ([a count] > 1)(或>= 2)。

【讨论】:

    【解决方案2】:

    嗯.. 听起来像一个字符串:@"foo("。在这种情况下,数组将只包含 @"foo" 并且它会崩溃(因为 count > 0,但不是 2!)。在访问 if ([a objectAtIndex:1] != [NSNull null]) { 中的第二个元素之前,您需要检查数组是否至少包含 2 个元素

    【讨论】:

      【解决方案3】:

      你可以这样做:

      NSString *str = @"asdf(asdf)asdf";
          NSRange range;
          range = [str rangeOfString:@"("];
          if( range.location != NSNotFound ){
              int start = range.location;
              range = [str rangeOfString:@")"];
              if( range.location!= NSNotFound ){
                  int end = range.location;
                  NSLog(@"%@",[NSString stringWithFormat:@"%@%@",[str substringToIndex:start],[str substringFromIndex:end+1]]);
              }
              // return nil;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-14
        • 2010-11-10
        • 2012-06-23
        • 2014-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多