Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 字符串操作方法的帮助_Objective C_Xcode_Ios4_String_Nsarray - Fatal编程技术网

Objective c 字符串操作方法的帮助

Objective c 字符串操作方法的帮助,objective-c,xcode,ios4,string,nsarray,Objective C,Xcode,Ios4,String,Nsarray,我有一个名为getTitle的方法,它位于NSString类别中,它将删除字符串和之间的任何内容,它还将删除这些字符串。但是,当输入字符串不包含上述任何一个字符串时,该方法将因以下错误而崩溃: *由于未捕获的异常“NSRangeException”而终止应用程序,原因:“*-[NSArray objectAtIndex:]:索引1超出边界[0..0]” 这是由于NSArray“a”没有对象造成的 然而,我似乎无法修复它。请看一下下面的代码并指出问题所在 - (NSString *)getTitl

我有一个名为getTitle的方法,它位于NSString类别中,它将删除字符串和之间的任何内容,它还将删除这些字符串。但是,当输入字符串不包含上述任何一个字符串时,该方法将因以下错误而崩溃:

*由于未捕获的异常“NSRangeException”而终止应用程序,原因:“*-[NSArray objectAtIndex:]:索引1超出边界[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;
}

它可能在这一行崩溃了:

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

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

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

您可以执行以下操作:

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;
    }

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