ios - UITableView 'hidden' 部分导致每次拉动刷新时分配更多内存

标签 ios objective-c uitableview ios7

我在 Code Review 上发布了这个,但有人告诉我它作为一个 Stack Overflow 问题可能会更好,所以写这篇文章。

我有一个 UITableView,当用户点击该部分的标题时,我会“隐藏”该部分。我认为这是我想出的一个非常酷的实现,但事实证明,当这个部分被隐藏并且用户拉动刷新时,每次他们拉动刷新时(刷新完成后),大约 1-2MB 被添加到内存中。如果 UITableView 的部分没有隐藏并且它们拉动刷新,则不会分配额外的内存(正确的方式/行为)。我知道 1-2 MB 并不多,但它全部加起来。我在 Profiler 中找不到任何漏洞,所以这就是我来到这里的原因。

我可能忽略了某些事情或我的逻辑有缺陷,如果能提供任何帮助,我将不胜感激。抱歉下面的冗长代码:

更新:已解决的代码:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section)
    {
        case 0:
        {
            return [self friendRequests];
        }
        case 1:
        {
            return [self friends];
        }
        default:
        {
            if (self.showingBlockedUsers == YES)
            {
                return [self blockedUsers];
            }
            else
            {
                return 0;
            }
        }
    }
}

原始问题的旧代码:

- (void)refreshing:(UIRefreshControl *)refreshControl
{
    [refreshControl beginRefreshing];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://foobar.com/test.plist"]];
    request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
    request.timeoutInterval = 5.0;

    [NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:
     ^(NSURLResponse *response, NSData *data, NSError *connectionError)
     {
         if (data)
         {
             NSPropertyListFormat format;

             NSMutableDictionary *dictionary = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:&format error:nil];

             self.tableDataSource = dictionary;
             [self.tableView reloadData];
             [refreshControl endRefreshing];
             [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
         }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    NSString *identifier = @"cellIdentifier";
    UILabel *userNameLabel = [self userNameLabel];
    UIView *requestsView = [self requestsView];
    UIButton *approveButton = [self approveButton];
    UIButton *denyButton = [self denyButton];
    UIImageView *profileImageView = [self profileImageView];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;

        [requestsView addSubview:approveButton];
        [requestsView addSubview:denyButton];

        [cell.contentView addSubview:requestsView];
        [cell.contentView addSubview:profileImageView];
        [cell.contentView addSubview:userNameLabel];
    }

    if (indexPath.section == 0)
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        userNameLabel.frame = CGRectMake(82, 0, 167, 68);
        approveButton.tag = indexPath.row;
        denyButton.tag = indexPath.row;

        NSArray *keys = [self.tableDataSource objectForKey:@"Requests"];
        id aKey = [keys objectAtIndex:indexPath.row];

        userNameLabel.text = [aKey objectForKey:@"User"];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[aKey objectForKey:@"URL"]]];
        request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
        request.timeoutInterval = 5.0;

        if ([imageCache objectForKey:aKey])
        {
            profileImageView.image = [imageCache objectForKey:aKey];
        }
        else
        {
            [NSURLConnection sendAsynchronousRequest:request
                                               queue:[NSOperationQueue mainQueue]
                                   completionHandler:
             ^(NSURLResponse *response, NSData *data, NSError *error)
             {
                 if (data)
                 {
                     dispatch_async(dispatch_get_main_queue(), ^
                    {
                        profileImageView.image = [UIImage imageWithData:data];
                        [imageCache setObject:[UIImage imageWithData:data] forKey:aKey];
                    });
                 }
                 else
                 {
                     profileImageView.image = [self profileImage];
                 }
             }];
        }
    }
    else if (indexPath.section == 1)
    {
        requestsView.hidden = YES;
        NSArray *keys = [self.tableDataSource objectForKey:@"Friends"];
        id aKey = [keys objectAtIndex:indexPath.row];
        userNameLabel.text = [aKey objectForKey:@"User"];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[aKey objectForKey:@"URL"]]];
        request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
        request.timeoutInterval = 5.0;

        if ([imageCache objectForKey:aKey])
        {
            profileImageView.image = [imageCache objectForKey:aKey];
        }
        else
        {
            [NSURLConnection sendAsynchronousRequest:request
                                               queue:[NSOperationQueue mainQueue]
                                   completionHandler:
             ^(NSURLResponse *response, NSData *data, NSError *error)
             {
                 if (data)
                 {
                     dispatch_async(dispatch_get_main_queue(), ^
                    {
                        profileImageView.image = [UIImage imageWithData:data];
                        [imageCache setObject:[UIImage imageWithData:data] forKey:aKey];
                    });
                 }
                 else
                 {
                     profileImageView.image = [self profileImage];
                 }
             }];
        }
    }
    else if (indexPath.section == 2)
    {
        requestsView.hidden = YES;
        NSArray *keys = [self.tableDataSource objectForKey:@"Blocked"];
        id aKey = [keys objectAtIndex:indexPath.row];
        userNameLabel.text = [aKey objectForKey:@"User"];
    }

    return cell;
}

- (void)displayBlockedUsers
{
    if (self.showingBlockedUsers == YES)
    {
        self.showingBlockedUsers = NO;
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
    }
    else
    {
        self.showingBlockedUsers = YES;
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
    }
}

- (NSInteger)friendRequests
{
    return [[self.tableDataSource objectForKey:@"Requests"]count];
}

- (NSInteger)friends
{
    return [[self.tableDataSource objectForKey:@"Friends"]count];
}

- (NSInteger)blockedUsers
{
    return [[self.tableDataSource objectForKey:@"Blocked"]count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2 && self.showingBlockedUsers == NO)
    {
        return 0;
    }
    else
    {
       return 68;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        if ([self friendRequests] < 1)
        {
            return 0;
        }
        else
        {
            return 22;
        }
    }
    else if (section == 1)
    {
        if ([self friends] < 1)
        {
            return 0;
        }
        else
        {
            return 22;
        }
    }
    else
    {
        if ([self blockedUsers] < 1)
        {
            return 0;
        }
        else
        {
            return 22;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section)
    {
        case 0:
        {
            return [self friendRequests];
        }
        case 1:
        {
            return [self friends];
        }
        default:
        {
            return [self blockedUsers];
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc]init];
    headerView.backgroundColor = [UIColor colorWithRed:248.0/255.0 green:248.0/255.0 blue:248.0/255.0 alpha:1.0];

    UILabel *headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, 0, 320, 22)];
    headerLabel.font = [UIFont systemFontOfSize:13.5];
    [headerView addSubview:headerLabel];

    if (section == 0)
    {
        NSInteger friendRequests = [self friendRequests];

        if (friendRequests < 2)
        {
            headerLabel.text = [NSString stringWithFormat:@"%d Request",friendRequests];
        }
        else
        {
            headerLabel.text = [NSString stringWithFormat:@"%d Requests",friendRequests];
        }
    }
    else if (section == 1)
    {
        NSInteger friends = [self friends];

        if (friends < 2)
        {
            headerLabel.text = [NSString stringWithFormat:@"%d Friend",friends];
        }
        else
        {
            headerLabel.text = [NSString stringWithFormat:@"%d Friends",friends];
        }
    }
    else
    {
        UIButton *theButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [theButton addTarget:self action:@selector(displayBlockedUsers) forControlEvents:UIControlEventTouchUpInside];
        theButton.frame = CGRectMake(0, 0, 320, 22);

        [headerView addSubview:theButton];

        NSInteger blocked = [self blockedUsers];

        if (self.showingBlockedUsers == YES)
        {
            headerLabel.text = [NSString stringWithFormat:@"%d Blocked - Tap to Hide",blocked];
        }
        else
        {
            headerLabel.text = [NSString stringWithFormat:@"%d Blocked - Tap to Show",blocked];
        }
    }

    return  headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
   return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

最佳答案

您似乎通过在 heightForRowAtIndexPath: 中返回 0 来隐藏该部分。这种方法的问题在于表格 View 仍会创建这些单元格 - 因此除了为实际显示的所有单元格创建单元格之外,表格 View 还为所有被阻止的用户创建额外的单元格。

要隐藏一个部分,只需在部分“关闭”时从 tableView:numberOfRowsInSection: 返回 0。这样, TableView 将不会调用 heightForRowAtIndexPath:cellForRowAtIndexPath: 或其他任何内容,因为您告诉它那里没有单元格。

关于ios - UITableView 'hidden' 部分导致每次拉动刷新时分配更多内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21942603/

相关文章:

ios - 分组 UITableView 顶部有奇怪的空间?

ios - 警告 ITMS-90080 : "The executable ' Payload/myapp. app/Frameworks/some-framework.framework' 不是与位置无关的可执行文件

ios - 弹出广告有效,但不是在我实现应用内购买后将其删除?

iphone - 背景图像不会扩展到 TableView 单元格中的附件 View 背景

objective-c - URL 减去 Objective-C 中的查询字符串

ios - 如何在不更改原始内容的情况下操作 NSDictionary 内容的副本

ios - 根据服务器的响应动态创建 UIButton

ios - 如何在 uisearchbar 搜索的谷歌地图上显示位置?

iphone - 我可以在 fetchedResultsController 中使用多个sectionNameKeyPath吗?

ios - 未调用 headerViewForSection