【问题标题】:Objective-C throws NSInvalidArgumentException with Dictionaries & ArraysObjective-C 用字典和数组抛出 NSInvalidArgumentException
【发布时间】:2010-08-27 03:39:46
【问题描述】:

我正在尝试按照教程并在我自己的代码中实现它。

这是我遇到的问题 -

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

- (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'

无论如何,我觉得我遗漏了一些东西...如果我遗漏了,请告诉我,我一定会尽快回复。

【问题讨论】:

    标签: objective-c arrays dictionary


    【解决方案1】:

    从您提供的代码来看,一切似乎都是正确的。问题可能出在其他地方。

    通常会发生选择器被发送到错误实例的错误,因为原始对象已被释放,并且已在其位置分配了不同类的新实例;一直以来,某些东西仍然引用旧的解除分配实例(在这种情况下,某个地方仍然认为 NSString 位于地址 0x59b5760,但该字符串已被解除分配,并且 NSDictionary 已分配在同一地址)。

    如果您使用NSZombieEnabled,运行时会将已释放的对象替换为僵尸对象,并且可以为您提供有关内存事故发生位置的更好线索。

    仔细修改代码的其他部分,确保所有代码遵循memory management rules。有时,只需要一次过度释放就会引起巨大的头痛。

    【讨论】:

      【解决方案2】:

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

      您需要在调试器中运行代码并设置 Break on Objective-C 异常选项。这将为您提供发生异常的代码行。

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

      【讨论】:

      • 我就是这么做的。从数组中取出一个对象并假设它是一个字符串:D 谢谢!
      猜你喜欢
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多