iOS 7 UITextView link detection crash in UITableView

前端 未结 3 2044
梦毁少年i
梦毁少年i 2020-12-31 11:26

I have a custom UITableView cell set up in my UITableView like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellFo         


        
3条回答
  •  梦谈多话
    2020-12-31 12:22

    The crash happens when two cells with data type are being dequeued while using the same cell identifier. It seems to be a bug in iOS, but Apple may have good reasons to implement it this way. (memory wise)

    And so the only 100% bullet proof solution is to provide a unique identifier for cells containing data types. This doesn't mean you will set a unique identifier to all cells in your table, of course, as it will eat up too much memory and your table scroll will be really slow.

    You can use NSDataDetector to determine if a matched type was found on your text, and only then save the found object as the cell identifier, like so:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    
        NSString *row = [self.dataSource objectAtIndex:indexPath.row];
        static NSDataDetector *detector = nil;
        if (!detector)
        {
            NSError *error = NULL;
            detector = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink | NSTextCheckingTypePhoneNumber error:&error];
        }
    
        NSTextCheckingResult *firstDataType = [detector firstMatchInString:row
                                                                   options:0
                                                                     range:NSMakeRange(0, [row length])];
        NSString *dataTypeIdentifier = @"0";
        if (firstDataType)
        {
            if (firstDataType.resultType == NSTextCheckingTypeLink)
                dataTypeIdentifier = [(NSURL *)[firstDataType URL] absoluteString];
            else if (firstDataType.resultType == NSTextCheckingTypePhoneNumber)
                dataTypeIdentifier = [firstDataType phoneNumber];
        }
    
        NSString *CellIdentifier = [NSString stringWithFormat:@"Cell_%@", dataTypeIdentifier];
    
        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    ...
    

    Note: Initializing NSDataDetector *detector as static rather than initialize it for each cell improves performance.

提交回复
热议问题