0

我知道这里有很多解决方案可以解决这个问题,但是我被困在一条线上,有时成功运行 n 有时会崩溃,我真的不知道为什么会这样......

这是我发布邮件的代码,我在其中收到错误-[__NSCFDictionary rangeOfString:]: unrecognized selector sent to instance

这是我在按下按钮时调用的方法的代码。

NSString* ingredientLine = [arrayOfIngredientList objectAtIndex:i];

NSArray* split ;

NSRange range = [ingredientLine rangeOfString:@"~"];

if (range.length > 0)
{
    split = [ingredientLine componentsSeparatedByString:@"~"];

    if( [split count] > 1 )
    {
        float amount = [[split objectAtIndex:0] floatValue];

        float actualAmount = amount*((float)recipeServings/(float)4);

        //parse the float if its 1.00 it becomes only 1

        NSString* amnt = [NSString stringWithFormat:@"%.1f", actualAmount];

        NSArray* temp = [amnt componentsSeparatedByString:@"."];

        if([[temp objectAtIndex:1] isEqualToString: @"0"])

            amnt = [temp objectAtIndex:0];

        if( actualAmount == 0.0 )

            amnt = @"";

        [amnt stringByReplacingOccurrencesOfString:@".0" withString:@""];

        NSLog(@"Amount is : %@",[split objectAtIndex:1]);

        strAmount = [@"" stringByAppendingFormat:@"%@ %@",amnt,[split objectAtIndex:1]];

        NSLog(@"Ingredient is : %@", strAmount);

        strIngedient = [split objectAtIndex:2];

    }
    else //ingredients header
    {
        //[[cell viewWithTag:10] setHidden:YES];
        strIngedient = [split objectAtIndex:0];
    }
}
else 
{

}

strIngredientsInfo = [strIngredientsInfo stringByAppendingFormat:@"%@ - %@ </br>",strAmount,strIngedient];

由于应用程序崩溃

    NSArray* split ;

NSRange range = [ingredientLine rangeOfString:@"~"];

if (range.length > 0)
{
    split = [ingredientLine componentsSeparatedByString:@"~"];
    }

请帮忙。

请建议为什么它会崩溃????:(

4

1 回答 1

2

发生这种情况是因为有时这段代码:

[arrayOfIngredientList objectAtIndex:i]

返回 an 的实例,NSDictionary而不是NSString您期望的。这样做是因为您事先NSDictionary在该数组中存储了一个。

因此,我不知道该数组有多大,以及将其全部内容打印出来以查看发生了什么是否可行,但这里有一些东西可以帮助您调试。在它崩溃的部分中,将其更改为:

if ( ! [ingredientLine respondsToSelector:@selector(rangeOfString:)] ) {
    NSLog(@"ingredientLine is not an NSString! It is a: %@", ingredientLine);
} else {
    NSRange range = [ingredientLine rangeOfString:@"~"];
}

您还可以在该NSLog行上放置一个断点以查看发生了什么。请注意,这将阻止您的崩溃,但不能解决根本问题。这只是帮助您调试真正问题的建议,即您将NSDictionary实例放入arrayOfIngredientList.

编辑:对这里发生的事情的一些解释可能会对您有所帮助。该if语句检查 所指向的对象是否ingredientLine不响应消息rangeOfString:。即使您已声明ingredientLineNSString *,您也可以轻松地将其分配给完全不同的类的实例,在这种情况下,它将不再是NSString实例并且将无法响应NSString的消息。请注意,您也可以说:

`if ( ! [ingredientList isKindOfClass:[NSString class]] )`

这将在这里做同样的工作。但是我使用respondsToSelector:它,因为它是在 Objective C 中了解的非常有用的信息。

于 2011-12-23T14:05:45.440 回答