代码之家  ›  专栏  ›  技术社区  ›  Christian Stewart

Objective-C使用字典和数组抛出NSInvalidArgumentException

  •  1
  • Christian Stewart  · 技术社区  · 14 年前

    我试图遵循一个教程,并在我自己的代码实现它。

    这就是我遇到的问题-

    data、wishlists和wishlistid都是nsmutablearray。我知道这个问题发生在我试图将字典添加到数据数组的行上。看看代码:

    - (void)setupWishlists:(NSString *)informationReturned
    {
        if(![informationReturned isEqualToString:@""]){
            //[data setArray:[informationReturned componentsSeparatedByString:@"."]]; //this works too, its an old method I kept just incase... this one has the raw combined wishlists name and id together. Here I attempt to split them.
    
            NSMutableArray *temporaryArray = [NSMutableArray array];
            NSArray *rawArray = [informationReturned componentsSeparatedByString:@"."];
            for (NSString *item in rawArray) {
                //so pretty much here we have the raw information that came back... remove the IDs
                [temporaryArray setArray:[item componentsSeparatedByString:@","]];
                [wishlists addObject:[temporaryArray objectAtIndex:0]];
                [wishlistids addObject:[temporaryArray objectAtIndex:1]];
            }
            //Initialize the array.
            NSDictionary *myWishlistsDict = [NSDictionary dictionaryWithObject:[NSArray arrayWithArray:wishlists] forKey:@"My Wishlists"];
    
            [data addObject:myWishlistsDict]; //GETTING PROBLEM HERE!!! IF I COMMENT THIS LINE IT IS FINE   
        }
        NSLog(@"Raw Wishlists Array: %@", [data description]);
    }
    

    另外,我确定要在这个函数之前运行的函数中分配所有这些数组等。

    data = [[NSMutableArray alloc] init];   
    wishlists = [[NSMutableArray alloc] init];
    wishlistids = [[NSMutableArray alloc] init];
    

    这是错误(在控制台中看到:

    2010-08-26 19:53:47.598 LoginApp[7604:207] -[__NSCFDictionary isEqualToString:]: unrecognized selector sent to instance 0x59b5760
    2010-08-26 19:53:47.600 LoginApp[7604:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary isEqualToString:]: unrecognized selector sent to instance 0x59b5760'
    

    不管怎样我觉得我漏掉了什么。。。如果我有请告诉我,我一定会很快回答。

    2 回复  |  直到 8 年前
        1
  •  0
  •   JeremyP    14 年前

    你关于错误发生在哪里的评论并不完全正确。将字典添加到数组不会导致无法识别的选择器异常。

    原因要么是某个地方的过度释放,在这种情况下,dreamlax的答案应该可以帮助您找到问题,要么您只是从数据数组中取出一个对象,并假设它是一个字符串,而不是。

        2
  •  1
  •   dreamlax    14 年前

    通常情况下,将选择器发送到错误实例的错误会发生,因为原始对象已被释放,而另一个类的新实例已在其位置被分配;同时,某些对象仍然引用旧的已释放实例(在本例中,某处仍有人认为NSString位于地址0x59b5760,但该字符串已被释放,并且NSDictionary已分配到同一地址)。

    如果你使用 NSZombieEnabled

    仔细修改代码的其他部分,以确保 全部的 代码的 memory management rules . 有时,只需一次过度释放就会引起剧烈的头痛。