• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

iphone - UITableView cellForRowAtIndexPath 导致滚动缓慢

[复制链接]
菜鸟教程小白 发表于 2022-12-11 21:47:19 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我的表格滚动非常缓慢,我认为这是由我的 cellForRowAtIndexPath 中的核心数据方法引起的。下面是我的 cellForRowAtIndexPath 方法:

- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

NSManagedObject *info = [buildingArray objectAtIndex: [indexPath row]];
// all rooms have been scanned for building
if([self allRoomsScanned: [[info valueForKey"buildingid"] intValue]]) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    [cell.textLabel setTextColor: [UIColor lightGrayColor]];
}
else {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    [cell.textLabel setTextColor: [UIColor blackColor]];
}
[cell.textLabel setFont:[UIFont fontWithName"Helvetica-Bold" size:16.0]];
[cell.textLabel setText:[info valueForKey"buildingname"]];

return cell;
}

这里是 allRoomsScanned 方法和 allDevicesScanned 方法:

- (BOOL) allRoomsScanned: (int) buildingID {
NSMutableArray *scannedRoomArray = [[NSMutableArray alloc] init];
// Get all user_device
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription 
                               entityForName"user_device" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
NSNumber *deviceid = [NSNumber numberWithInt: 0];
NSNumber *roomid = [NSNumber numberWithInt: 0];
//int lastRoomID = 0;

for (NSManagedObject *info in fetchedObjects) {
    // Get all device
    deviceid = [info valueForKey"deviceid"];
    fetchRequest = [[NSFetchRequest alloc] init];
    entity = [NSEntityDescription 
              entityForName"device" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];

    NSPredicate *predicate = [NSPredicate predicateWithFormat"(deviceid = %d)", [deviceid intValue]];
    [fetchRequest setPredicate:predicate]; 
    NSArray *fetchedDevices = [context executeFetchRequest:fetchRequest error:&error];
    for (NSManagedObject *infod in fetchedDevices) {
        // Get all room
        roomid = [infod valueForKey"roomid"];
        fetchRequest = [[NSFetchRequest alloc] init];
        entity = [NSEntityDescription 
                  entityForName"room" inManagedObjectContext:context];
        [fetchRequest setEntity:entity];

        NSPredicate *predicate = [NSPredicate predicateWithFormat"(roomid = %d) AND (buildingid = %d)", [roomid intValue], buildingID];
        [fetchRequest setPredicate:predicate]; 
        NSMutableArray *fetchedRoom = [[context executeFetchRequest:fetchRequest error:&error] mutableCopy];

        // add room to array if room belongs to selected building and room not already added
        if([fetchedRoom count] > 0) { //&& lastRoomID != [roomid intValue]) {
            for (NSManagedObject *info in fetchedRoom) {
                NSLog(@"room id: %@", [info valueForKey:@"roomid"]);
                // add room ids to array if not already there
                if (![scannedRoomArray containsObject:[info valueForKey:@"roomid"]] && [self allDevicesScanned:[[info valueForKey:@"roomid"] intValue]])
                    [scannedRoomArray addObject: [info valueForKey:@"roomid"]];
            }
            //lastRoomID = [roomid intValue];
        }
    }
}

fetchRequest = [[NSFetchRequest alloc] init];
entity = [NSEntityDescription 
          entityForName:@"room" inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(buildingid = %d)", buildingID];
[fetchRequest setPredicate:predicate]; 
NSArray *fetchedRoomTotal = [context executeFetchRequest:fetchRequest error:&error];
//NSLog(@"Total Rooms for Building: %d", [fetchedRoomTotal count]);
//NSLog(@"Scanned Rooms for Building: %d", [scannedRoomArray count]);
//NSLog(@"Scanned rooms: %@", scannedRoomArray);
if([fetchedRoomTotal count] == [scannedRoomArray count] && [fetchedRoomTotal count] > 0) {
    return YES;
}
else {
    return NO;
}
}

- (BOOL) allDevicesScanned: (int) roomID {
NSMutableArray *scannedDeviceArray = [[NSMutableArray alloc] init];
// Get all user_device
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription 
                               entityForName:@"user_device" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
NSNumber *deviceid = [NSNumber numberWithInt: 0];
//NSNumber *roomid = [NSNumber numberWithInt: 0];

for (NSManagedObject *info in fetchedObjects) {
    // Get all device
    deviceid = [info valueForKey:@"deviceid"];
    fetchRequest = [[NSFetchRequest alloc] init];
    entity = [NSEntityDescription 
              entityForName:@"device" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(deviceid = %d) AND (roomid = %d)", [deviceid intValue], roomID];
    [fetchRequest setPredicate:predicate]; 
    NSArray *fetchedDevices = [context executeFetchRequest:fetchRequest error:&error];
    for (NSManagedObject *infod in fetchedDevices) {

        // add device to array
        if([fetchedDevices count] > 0) {
            NSLog(@"room id: %d", roomID);
            // add device ids to array if not already there
            if (![scannedDeviceArray containsObject:deviceid])
                [scannedDeviceArray addObject: deviceid];
        }
    }
}

fetchRequest = [[NSFetchRequest alloc] init];
entity = [NSEntityDescription 
          entityForName:@"device" inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(roomid = %d)", roomID];
[fetchRequest setPredicate:predicate]; 
NSArray *fetchedDeviceTotal = [context executeFetchRequest:fetchRequest error:&error];
//NSLog(@"Total Devices for Room: %d", [fetchedDeviceTotal count]);
//NSLog(@"Scanned Devices for Room: %d", [scannedDeviceArray count]);
//NSLog(@"Scanned Devices: %@", scannedDeviceArray);
if([fetchedDeviceTotal count] == [scannedDeviceArray count] && [fetchedDeviceTotal count] > 0) {
    return YES;
}
else {
    return NO;
}
}

关于如何消除滚动时的延迟有什么想法吗?我假设我的核心数据调用或在 cellForRowAtIndexPath 中调用方法的方式可能效率低下。

感谢您的帮助。非常感谢。



Best Answer-推荐答案


你真的不应该在滚动表格 View 时在主线程上进行 Fetch Requests 和处理。 正如 rokjarc 所说,您绝对应该保存(相当繁重的) allRoomsScanned 方法的结果。我建议添加一种新样式,即带有事件指示器,当您还没有该输入的结果时,单元格会获得该样式。加载完成后,您刷新表格 View 单元格。

注意:您不能在 allRoomsScannedallDevicesScanned 中使用默认的 NSManagedObjectContext。 您需要在后台线程中初始化一个新的上下文。要么在 block 的开头初始化一个新的上下文并将其作为方法参数传递,要么在方法中创建一个新的。

NSManagedObject *info = [buildingArray objectAtIndex: [indexPath row]];

NSNumber *cachedResult = [self.scanResults objectForKey:info.objectID];
if (cachedResult == nil) {
    // style loading state

    int scanInfo = [[info valueForKey:@"buildingid"] intValue];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        BOOL result = [self allRoomsScanned: scanInfo];
        [self.scanResults setObject:[NSNumber numberWithBool:result] forKey:info.objectID];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]
    });

} else if (cachedResult.boolValue == YES) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    [cell.textLabel setTextColor: [UIColor lightGrayColor]];
} else if (cachedResult.boolValue == NO) {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    [cell.textLabel setTextColor: [UIColor blackColor]];
}

[cell.textLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:16.0]];
[cell.textLabel setText:[info valueForKey:@"buildingname"]];

return cell;

关于iphone - UITableView cellForRowAtIndexPath 导致滚动缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9622776/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap