使用Magical Record的核心数据的异步UITableViewController

时间:2014-11-06 14:15:38

标签: ios objective-c uitableview asynchronous magicalrecord

我很长时间使用Magical Record进行异步UITableViewController。 在我的表中,我有两种类型的子类自定义UITableViewCell。 其中一个,包含一个大图像。 在表中可以有很多这类消息。

这使得我的桌子滚动非常糟糕。

我很乐意帮忙,因为我被困住了,我的tableView看起来很糟糕。

这是我的代码:

MainTableViewController:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id typeOfCell;

    CoreDataPhotoRecord *photoDetails;

    if (tableView == self.searchDisplayController.searchResultsTableView) {
        photoDetails = self.searchResults[indexPath.row];
    }
    else {
        photoDetails = [HumanResponse allAcceptedRecords][indexPath.row];
    }

    switch (photoDetails.message.type.integerValue) {
        case NORMAL_MESSAGE:
        {
            MessageTableViewCell *cell = (MessageTableViewCell *)[tableView dequeueReusableCellWithIdentifier:kMessageCellID];
            if (!cell) {
                cell = (MessageTableViewCell *)[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kMessageCellID];
            }

            typeOfCell = cell;

            break;
        }
        case GENERAL_MESSAGE:
        case TOTAL_MESSAGE:
        case SHARE_MESSAGE:
        {
            ShareTableViewCell *cell = (ShareTableViewCell *)[tableView dequeueReusableCellWithIdentifier:kShareCellID];
            if (!cell) {
                cell = (ShareTableViewCell *)[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kShareCellID];
            }

            typeOfCell = cell;

            break;
        }
    }

    typeOfCell = [self configureCell:typeOfCell
                           tableView:tableView
                           indexPath:indexPath
                        photoDetails:photoDetails];

    return typeOfCell;
}

- (id)configureCell:(id)cell
          tableView:(UITableView *)tableView
          indexPath:(NSIndexPath *)indexPath
       photoDetails:(CoreDataPhotoRecord *)photoDetails
{
    // Set data with fail-safe
    if ([cell respondsToSelector:@selector(setParentView:)]) {
        [cell setParentView:self];
    }
    if ([cell respondsToSelector:@selector(setIndexPath:)]) {
        [cell setIndexPath:indexPath];
    }
    if ([cell respondsToSelector:@selector(setTag:)]) {
        [cell setTag:indexPath.row];
    }
    if ([cell respondsToSelector:@selector(configureWithMessage:)]) {
        [cell configureWithMessage:photoDetails];
    }
    if (photoDetails.message.type.integerValue == NORMAL_MESSAGE) {
        if ([cell respondsToSelector:@selector(setImageViewRepresentative:)]) {
            [cell imageViewRepresentative].layer.masksToBounds = YES;
            [cell imageViewRepresentative].layer.borderColor = [UIColor whiteColor].CGColor;
            [cell imageViewRepresentative].layer.borderWidth = 1;
            [cell imageViewRepresentative].layer.cornerRadius = 20;
        }
    }


    if (tableView.isEditing) {
        [cell setSelectionStyle:UITableViewCellSelectionStyleDefault];
    } else {
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }

    /* if (photoDetails.message.type.integerValue == NORMAL_MESSAGE) {
        switch (photoDetails.state.integerValue) {
            case PhotoRecordStateDownloaded: {
                //
                break;
            }
            case PhotoRecordStateFailed: {
                //
                break;
            }
            case PhotoRecordStateNew: {
                if (!tableView.dragging && !tableView.decelerating) {
                    [self.asyncOperations startOperationsForPhotoRecord:photoDetails indexPath:indexPath];
                }
                break;
            }
        }
    } */

    return cell;
}

ShareTableViewCell:

- (void)configureWithMessage:(CoreDataPhotoRecord *)photoDetails
{
    self.photoDetails = photoDetails;

    __weak typeof(self) weakSelf = self;

    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:self.photoDetails.message.imageURL];
    urlRequest.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
    UIImage *placeholderImage = [UIImage imageNamed:@"default_246.jpg"];

    [[UIImageView new] setImageWithURLRequest:urlRequest
                     placeholderImage:placeholderImage
                            messageID:self.photoDetails.message.message_id
                              success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
    {
        if (image) {
            if (![weakSelf.photoDetails.image isEqualToData:UIImagePNGRepresentation(weakSelf.backgroundButton.currentBackgroundImage)]) {
                if ([NSThread isMainThread]) {
                    [weakSelf.backgroundButton setBackgroundImage:image forState:UIControlStateNormal];
                }
                else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.backgroundButton setBackgroundImage:image forState:UIControlStateNormal];
                    });
                }
            }

        }
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
    {
        NSLog(@"%s, failure: %@", __PRETTY_FUNCTION__, error.localizedDescription);

        if ([NSThread isMainThread]) {
            [weakSelf.backgroundButton setBackgroundImage:placeholderImage forState:UIControlStateNormal];
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.backgroundButton setBackgroundImage:placeholderImage forState:UIControlStateNormal];
            });
        }
    }];

    self.labelRepresentativeName.text = HRLocalizedString(@"app_name");

    if (self.photoDetails.message.textColor.integerValue == DARK_GRAY_COLOR) {
        self.labelRepresentativeName.textColor = [UIColor darkGrayColor];
        self.labelText.textColor = [UIColor darkGrayColor];
        self.labelText2.textColor = [UIColor darkGrayColor];
        self.labelTime.textColor = [UIColor darkGrayColor];

        [self.btnDelete setBackgroundImage:[UIImage imageNamed:@"trash_gray.png"] forState:UIControlStateNormal];
        [self.btnDelete setBackgroundImage:[UIImage imageNamed:@"trash_gray_pressed.png"] forState:UIControlStateHighlighted];
    }
    else {
        self.labelRepresentativeName.textColor = [UIColor whiteColor];
        self.labelText.textColor = [UIColor whiteColor];
        self.labelText2.textColor = [UIColor whiteColor];
        self.labelTime.textColor = [UIColor whiteColor];


        [self.btnDelete setBackgroundImage:[UIImage imageNamed:@"trash.png"] forState:UIControlStateNormal];
        [self.btnDelete setBackgroundImage:[UIImage imageNamed:@"trash_pressed.png"] forState:UIControlStateHighlighted];
    }

    self.mySecretMessage = self.photoDetails.message.text;

    HRCalendarUnit calendarUnit = [Utilities relativeDateFormDate:[Utilities dateFromString:self.photoDetails.message.date]];

    if (calendarUnit == HRCalendarUnitToday) {
        self.labelTime.text = HRLocalizedString(@"today");
    }
    else if (calendarUnit == HRCalendarUnitYesterday) {
        self.labelTime.text = HRLocalizedString(@"yesterday");
    }
    else {
        self.labelTime.text = [self getCeanDate:self.photoDetails.message.date];
    }

    self.labelText.text = self.mySecretMessage;
}

的UIImageView +异步:

- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
              placeholderImage:(UIImage *)placeholderImage
                       messageID:(NSString *)message_id
                       success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
                       failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{    
    CoreDataPhotoRecord *photoDetails = [self imageExists:message_id];

    if (photoDetails.state.integerValue == PhotoRecordStateNew || photoDetails.state.integerValue == PhotoRecordStateFailed) {
        if (placeholderImage) self.image = placeholderImage;

        __block NSURLResponse *urlResponse;
        __block NSData *data;
        __block NSError *connectionError;

        [appDelegate.imageQueue addOperationWithBlock:^{
            data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&urlResponse error:&connectionError];

            if (data) {
                if (success) {
                    appDelegate.sharedCache[photoDetails.message.imageURL] = [UIImage imageWithData:data];

                    [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
                        CoreDataPhotoRecord *newPhotoDetails = [photoDetails MR_inContext:localContext];
                        if (newPhotoDetails) {
                            newPhotoDetails.image = data;
                            newPhotoDetails.state = [NSNumber numberWithInteger:PhotoRecordStateDownloaded];
                        }
                    }];

                    success(urlRequest, (NSHTTPURLResponse *)urlResponse, appDelegate.sharedCache[photoDetails.message.imageURL]);
//                    success(urlRequest, (NSHTTPURLResponse *)urlResponse, [UIImage imageWithData:data]);
                }
            }
            else {
                [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
                    CoreDataPhotoRecord *newPhotoDetails = [photoDetails MR_inContext:localContext];
                    if (newPhotoDetails) {
                        newPhotoDetails.state = [NSNumber numberWithInteger:PhotoRecordStateFailed];
                    }
                }];

                if (failure) {
                    failure(urlRequest, (NSHTTPURLResponse *)urlResponse, connectionError);
                }
            }
        }];
    }
    else {
//        if (success) {
//            success(urlRequest, nil, appDelegate.sharedCache[photoDetails.message.imageURL]);
//        }
        if (success) success(urlRequest, nil, [UIImage imageWithData:photoDetails.image]);
    }
}

我正在尝试这么多方式(而且我知道它很糟糕)但是没有任何东西能让我获得很好的快速滚动感。

0 个答案:

没有答案