【问题标题】:'-[__NSDictionaryI length]: unrecognized selector sent to instance' - trying to figure out why'-[__NSDictionaryI length]: unrecognized selector sent to instance' - 试图找出原因
【发布时间】:2014-04-29 08:25:24
【问题描述】:

我有一个 UITableView 自定义 UILabel 作为标题,另一个是副标题,以便将文本向右对齐。

我的数据来自网络服务,我解析并存储在NSArrayNSDictionary 中。 一些标题或副标题可以是 nil/empty-text。 为此,我将其放入 try/catch 中。

我的表格中的一行让我的应用迷恋,我不知道为什么。

我认为其中一个(标题/副标题)返回为 NSDictionary,但我为我的对象的类打印了日志打印,对于我的 [UILabel text],似乎一切正常。

异常和堆栈跟踪:

2014-04-29 10:47:55.985 Cellular Radar[3226:60b] -[__NSDictionaryI length]: unrecognized selector sent to instance 0x16d007f0
2014-04-29 10:47:55.993 Cellular Radar[3226:60b] -[Home tableView:willDisplayCell:forRowAtIndexPath:], exception.reason: -[__NSDictionaryI length]: unrecognized selector sent to instance 0x16d007f0
2014-04-29 10:47:55.999 Cellular Radar[3226:60b] -[__NSDictionaryI length]: unrecognized selector sent to instance 0x16d007f0
2014-04-29 10:47:56.006 Cellular Radar[3226:60b] CRASH:
-[__NSDictionaryI length]: unrecognized selector sent to instance 0x16d007f0
2014-04-29 10:47:56.062 Cellular Radar[3226:60b] Stack Trace:
(
    0   CoreFoundation                      0x30e02feb <redacted> + 154
    1   libobjc.A.dylib                     0x3b5b1ccf objc_exception_throw + 38
    2   CoreFoundation                      0x30e06967 <redacted> + 202
    3   CoreFoundation                      0x30e05253 <redacted> + 706
    4   CoreFoundation                      0x30d547b8 _CF_forwarding_prep_0 + 24
    5   UIKit                               0x33637ed3 <redacted> + 38
    6   UIKit                               0x337595bb <redacted> + 3682
    7   UIKit                               0x33758031 <redacted> + 60
    8   UIKit                               0x3361ed79 <redacted> + 380
    9   QuartzCore                          0x3329c62b <redacted> + 142
    10  QuartzCore                          0x33297e3b <redacted> + 350
    11  QuartzCore                          0x33297ccd <redacted> + 16
    12  QuartzCore                          0x332976df <redacted> + 230
    13  QuartzCore                          0x332974ef <redacted> + 314
    14  QuartzCore                          0x332eac49 <redacted> + 516
    15  IOMobileFramebuffer                 0x3606375d <redacted> + 104
    16  IOKit                               0x31aed451 IODispatchCalloutFromCFMessage + 248
    17  CoreFoundation                      0x30dc2ef9 <redacted> + 136
    18  CoreFoundation                      0x30dcdab7 <redacted> + 34
    19  CoreFoundation                      0x30dcda53 <redacted> + 346
    20  CoreFoundation                      0x30dcc227 <redacted> + 1398
    21  CoreFoundation                      0x30d36f0f CFRunLoopRunSpecific + 522
    22  CoreFoundation                      0x30d36cf3 CFRunLoopRunInMode + 106
    23  GraphicsServices                    0x35c3b663 GSEventRunModal + 138
    24  UIKit                               0x3368216d UIApplicationMain + 1136
    25  Cellular Radar                      0x00077757 main + 70
    26  libdyld.dylib                       0x3babeab7 <redacted> + 2
)
2014-04-29 10:47:56.075 Cellular Radar[3226:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI length]: unrecognized selector sent to instance 0x16d007f0'
*** First throw call stack:
(0x30e02fd3 0x3b5b1ccf 0x30e06967 0x30e05253 0x30d547b8 0x33637ed3 0x337595bb 0x33758031 0x3361ed79 0x3329c62b 0x33297e3b 0x33297ccd 0x332976df 0x332974ef 0x332eac49 0x3606375d 0x31aed451 0x30dc2ef9 0x30dcdab7 0x30dcda53 0x30dcc227 0x30d36f0f 0x30d36cf3 0x35c3b663 0x3368216d 0x77757 0x3babeab7)
libc++abi.dylib: terminating with uncaught exception of type NSException

相关代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    tableView.separatorColor = [UIColor lightGrayColor];

    UILabel *textLabel = (UILabel*)[cell viewWithTag:kTAG_TITLE];
    UILabel *detailTextLabel = (UILabel*)[cell viewWithTag:kTAG_SUBTITLE];
    UIImageView *imageView = (UIImageView*)[cell viewWithTag:kTAG_IMAGE];

    textLabel.frame = CGRectMake(
                                 textLabel.frame.origin.x,
                                 textLabel.frame.origin.y - 10,
                                 textLabel.frame.size.width,
                                 textLabel.frame.size.height
                                 );
    cell.textLabel.frame = textLabel.frame;

    cell.tag = indexPath.row;
    cell.backgroundColor = [UIColor whiteColor];

    cell.textLabel.font = cell.detailTextLabel.font = [UIFont fontWithName:kFONT_NAME size:kFONT_SIZE];

    imageView.layer.cornerRadius = 10.0;
    imageView.layer.borderColor = (__bridge CGColorRef)([UIColor clearColor]);
    imageView.layer.borderWidth = 0;
    imageView.clipsToBounds = YES;
    imageView.contentMode = UIViewContentModeScaleAspectFill;

    textLabel.text = @"";

    textLabel.textColor = [UIColor darkGrayColor];
    textLabel.backgroundColor = [UIColor clearColor];
    textLabel.textAlignment = NSTextAlignmentRight;
    textLabel.font = [UIFont fontWithName:kFONT_NAME size:kFONT_SIZE];
    textLabel.textColor = [UIColor darkGrayColor];

    detailTextLabel.text = @"";
    detailTextLabel.font = [UIFont fontWithName:kFONT_NAME size:kFONT_SIZE];
    detailTextLabel.backgroundColor = [UIColor clearColor];
    detailTextLabel.textAlignment = NSTextAlignmentRight;
    detailTextLabel.textColor = [UIColor darkGrayColor];

    if (self.arrayGlobal.count > 0)
    {
        NSDictionary *dict = self.arrayGlobal[indexPath.row];
        NSString *imageUrl = dict[@"imageUrl"];

        @try
        {
            cell.textLabel.text = dict[@"Title"];
        }
        @catch (NSException *exception)
        {
            NSLog(@"%s, %@", __PRETTY_FUNCTION__, exception.reason);

            cell.textLabel.text = @"";
        }

        @try
        {
            detailTextLabel.text = dict[@"Text"];
        }
        @catch (NSException *exception)
        {
            detailTextLabel.text = @"";
        }

        if (imageUrl.length > 0)
        {
            NSString *completeURL = @"";
            completeURL = [completeURL stringByAppendingString:kPROFILE_IMAGE_URL];
            completeURL = [completeURL stringByAppendingString:@"/2/"];
            completeURL = [completeURL stringByAppendingString:imageUrl];
            completeURL = [completeURL stringByAppendingString:@".png"];

            NSString *fileName = [NSString stringWithFormat:@"%@.png", imageUrl];
            NSString* path = GetMediaFolder();
            BOOL imageExists = [[NSFileManager defaultManager] fileExistsAtPath:[path stringByAppendingPathComponent:fileName]];

            if (imageExists)
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UITableViewCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];

                    UIImageView *imageView = (UIImageView*)[updateCell viewWithTag:kTAG_IMAGE];
                    imageView.image=[UIImage imageWithContentsOfFile:[path stringByAppendingPathComponent:fileName]];
                    imageView.layer.cornerRadius = 23.0;
                    imageView.layer.borderColor = (__bridge CGColorRef)([UIColor clearColor]);
                    imageView.layer.borderWidth = 1.0;
                    imageView.clipsToBounds = YES;
                    imageView.contentMode = UIViewContentModeScaleAspectFill;

                    [updateCell setNeedsLayout];
                });
            }
            else
            {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    NSURL *imageURL=[NSURL URLWithString:completeURL];
                    NSData *image=[NSData dataWithContentsOfURL:imageURL];
                    [image writeToFile:[path stringByAppendingPathComponent:fileName] atomically:YES];

                    // Update UI
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UITableViewCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];

                        UIImageView *imageView = (UIImageView*)[updateCell viewWithTag:kTAG_IMAGE];
                        imageView.image=[UIImage imageWithContentsOfFile:[path stringByAppendingPathComponent:fileName]];
                        imageView.layer.cornerRadius = 23.0;
                        imageView.layer.borderColor = (__bridge CGColorRef)([UIColor clearColor]);
                        imageView.layer.borderWidth = 1.0;
                        imageView.clipsToBounds = YES;
                        imageView.contentMode = UIViewContentModeScaleAspectFill;

                        [updateCell setNeedsLayout];
                    });
                });
            }
        }
    }
    return cell;
}

- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"4");

    @try {
        cell = [Netroads willDisplayFlatDesignCell:cell];
    }
    @catch (NSException *exception) {
        NSLog(@"%s, exception.reason: %@", __PRETTY_FUNCTION__, exception.reason);
    }
}

+ (UITableViewCell*)willDisplayFlatDesignCell:(UITableViewCell*)cell
{
    UILabel *label = [[UILabel alloc] initWithFrame:cell.frame];
    label.backgroundColor = [UIColor colorWithRed:200.0/255.0 green:200.0/255.0 blue:200.0/255.0 alpha:1]; // light gray color, native iphone
    cell.selectedBackgroundView = label;

    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.textLabel.textAlignment = NSTextAlignmentRight;
    cell.textLabel.textColor = [UIColor darkGrayColor];

    if (cell.detailTextLabel.text) {
        cell.detailTextLabel.backgroundColor = [UIColor clearColor];
        cell.detailTextLabel.textAlignment = NSTextAlignmentRight;
        cell.detailTextLabel.textColor = [UIColor darkGrayColor];
    }

    return cell;
}

编辑 - 1:

正如@sleepwalkerfx 指出的那样,我为我的 NSDictionary 制作了一个日志,而我喜欢的那一行的结果是:

2014-04-29 12:01:15.182 Cellular Radar[3331:60b] {
    Date = "22/01/14";
    Owner = "\U05de\U05e2\U05e8\U05db\U05ea";
    Text =     {
    };
    Time = "09:27";
    Title =     {
    };
    WallID = 1;
    imageUrl = system;
}

这让我觉得这些对象(文本、标题)如何通过[NSString class] 的检查?

【问题讨论】:

  • 请显示导致该问题的代码。可能是“家庭”类
  • 编辑了我的相关代码。
  • 添加一些校验码;无论你在哪里cell.textLabel.text,添加一个日志来检查你分配的字典元素from(即NSLog(@"text class = %@", NSStringFromClass([dict[@"Title"] class]));。你假设这些元素是字符串,而实际上是一个字典。
  • 如何添加一个异常断点并找到该死的错误!在断点检查器的底部单击“+”和“添加异常断点”。它应该指向代码中引发异常的行。
  • @user2260054 因为这会揭示错误的影响,而不是错误本身,这(我相信)是由将单元格的文本属性设置为字典而不是字符串(发生在与引发异常的位置不同)。

标签: ios objective-c uitableview


【解决方案1】:

您正在将单元格的 text 属性设置为字典:

cell.textLabel.text = dict[@"Title"];

来自您的dict日志:

Title =     {
    };

和:

detailTextLabel.text = dict[@"Text"];

来自您的dict日志:

Text =     {
    };

不清楚应该使用来自dict 的确切值,但不应该是那些字典。

【讨论】:

  • 实际上是公平的。但是,您的意思是@try{cell.textLabel.text = dict[@"Title"]} 吗?因为,@catch 不应该处理这种情况吗?
  • @user2260054 是的,但是其中带有 CRASH 的实际行不在 OP 发布的代码中。因此,任何人都可以猜测该行被写入日志的位置。我认为我的回答表明 OP 正在分配不兼容的对象实例,如果它没有显示崩溃的确切原因。
【解决方案2】:

原因:NSDictionary 没有 lengh 方法而 NSString 有

改变这一行

    if (imageUrl.length > 0)
    {

    if ([imageUrl isKindOfClass:[NSString class]] && imageUrl.length > 0)
    {

【讨论】:

  • 长度检查返回 6,然后我更改了您发布的代码,但我仍然有同样的错误。
【解决方案3】:

根据您的日志,您尝试以NSString 的身份访问NSDictionary 对象。这就是为什么它会导致上述错误。

问题应该在这里..

 NSString *imageUrl = dict[@"imageUrl"];

如果是字典,应该是crash在这一行..

if (imageUrl.length > 0)

【讨论】:

  • 这是您(问题的作者,我的意思是)访问@try 块之外的dict 字典的唯一行。几乎可以肯定,问题就在这里。
  • imageUrl 作为 NSString 对象返回。
  • 根据您对@Vijay 的评论,imageUrl 可能会使用 NSString 和 NSDictionary。也检查此检查并使用断点进行测试。 if ([imageUrl isKindOfClass:[NSDictionary class]) NSlog@("Image url is NSDictionary object")
【解决方案4】:

在你的tableView:willDisplayCell:forRowAtIndexPath:

检查这一行,

cell = [Netroads willDisplayFlatDesignCell:cell];

这个方法有问题,[Netroads willDisplayFlatDesignCell];

您正试图从NSDictionary 而不是NSArray 中获取length。如果您从 JSON Web 服务加载数据,您可能会将 NSDictionary 解析为 NSArray。修复那个方法,就不会崩溃了。

【讨论】:

  • 我没有看到我在哪里检查 NSDictionary 的长度,我错过了什么?
  • 可能您将字典转换为数组。如果您从 json 服务加载数据,请检查 [jsonObject objectForKey"yourKey"] 字段并确保您将该对象存储在正确的数据类型中。
  • 相应地编辑了我的问题。
  • @IdanMoshe 根据您的编辑,您所拥有的是字典。您不能在该对象上调用 length。你用哪种方法调用长度?如果对象是 NSDictionary,则添加条件语句以不迭代一定长度
猜你喜欢
  • 1970-01-01
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多