代码之家  ›  专栏  ›  技术社区  ›  suse

因iPhone应用程序的Objective-C中未捕获异常而终止应用程序

  •  -1
  • suse  · 技术社区  · 16 年前

    我在Objective-C中编写了一个for循环,这就是我的代码的样子

    NSString *string = [NSString stringWithContentsOfFile=@"/Users/Home/myFile.doc"];
    NSString *seperator=@"\n";
    NSArray *mainarray = [string componentsSeparatedByString:seperator];
    // Since i want to parse each element of mainarray
    for(NSString *s in mainarray)
    {
      //again parising the string using a new separator
        NSString newseparator = @"=";
        NSArray *subarray = [s componentsSeparatedByString : newseparator];
    
      //Copying the elements of array into key and object string variables
    
        NSString *key = [subarray objectAtIndex:0];
        NSLog(@"%@",key);
        NSString *class_name= [subarray objectAtIndex:1];
        NSLog(@"%@",class_name);
    
       // create an instance for the class_name
          //dont knw how it ll take the value from file and ???  
    
     //Putting the key and objects values into hashtable 
        NSMutableDictionary = [NSDictionary dictinaryWithObject:class_name forKey:key];
    }
    

    每当我执行此代码时,这会使我的程序崩溃,并说,由于未捕获的异常而终止应用程序nsrangeexception

    如何知道数组的范围以及如何在for循环中指定终止条件?你说什么?请允许我知道如何处理这个例外?你说什么?

    1 回复  |  直到 16 年前
        1
  •  2
  •   bbum    16 年前

    我很惊讶代码甚至可以编译。如果我没记错的话,它就无法编译,除非您已经竭尽全力关闭了一大堆编译器警告。

    NSString newseparator = @";";
    

    这会给你一个错误,因为你没有*。

    NSString *key = [subarray objectAtIndex[0]];
    NSString *object = [subarray objectAtIndex[1]];
    

    这两行代码都没有任何意义。

    似乎你还没有发布实际的代码?


    现在,回到例外。如果试图访问数组中索引范围之外的某个索引项,则将引发范围异常。因此,如果 componentsSeparatedByString: 返回一个由0或1个元素组成的数组,然后 [subarray objectAtIndex: 1]; 将导致引发范围异常。

    你什么 不要 要做的是尝试使用 @catch 块。在Cocoa(和iPhone开发)中,异常被视为不可恢复的错误。

    因此,相反,使用 -count 方法来验证数组是否实际包含您期望的元素。因为您编写的是一个临时的解析器,所以最好将其作为输入有效性的最小检查。