草庐IT

ios - 具有复杂单元格的 UITableView 缓慢且滞后

coder 2024-01-11 原文

我几乎完成了我的应用程序,除了主视图之外一切似乎都正常工作。
它是一个带有嵌入式 UITableViewUIViewController
我使用 Parse 作为后端,并在我的 viewDidLoad 方法中获得了我需要的对象数组。

每个单元格都包含一些我在 tableView:cellForRowAtIndexPath 中获取的数据,恐怕这就是我的表格 View 如此缓慢的原因,但我不知道如何在没有 indexPath.row 编号的情况下获取数组中每个对象所需的数据。

我已经按照其他答案中的建议将每个单元格元素设为“不透明”。

这是我的代码,如有任何帮助,我们将不胜感激:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cellHT";
    CellHT *cell = (CellHT *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[CellHT alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:CellIdentifier];
    }

    // self.hH is an NSArray containing all the objects
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    cell.lblTitle.text = [self.hH[indexPath.row] objectForKey:@"title"];
    cell.lblVenueName.text = [self.hH[indexPath.row] objectForKey:@"venueName"];
    cell.lblDistance.text = NSLocalizedString(@"Distance from you", nil);
    self.geo = [self.hH[indexPath.row] objectForKey:@"coordinates"];

    // the formatters are initialized in the viewDidLoad: method
    self.formatData = [NSDateFormatter dateFormatFromTemplate:@"dd/MM" options:0 locale:[NSLocale currentLocale]];
    [self.formatterData setDateFormat:self.formatData];
    self.formatOra = [NSDateFormatter dateFormatFromTemplate:@"j:mm" options:0 locale:[NSLocale currentLocale]];
    [self.formatterOra setDateFormat:self.formatOra];
    self.dal = NSLocalizedString(@"from", nil);
    self.ore = NSLocalizedString(@"at", nil);
    CLLocation *vLoc = [[CLLocation alloc] initWithLatitude:self.geo.latitude longitude:self.geo.longitude];
    CLLocation *user = [[CLLocation alloc] initWithLatitude:self.userGeo.latitude longitude:self.userGeo.longitude];
    CLLocationDistance distance = [user distanceFromLocation:venueLoc];
    if ([[prefs objectForKey:@"unit"] isEqualToString:@"km"]) {
        cell.lblDist.text = [NSString stringWithFormat:@"%.1f Km", distance /1000];
    } else {
        cell.lblDist.text = [NSString stringWithFormat:@"%.1f Miles", distance /1609];
    }

    // compare the object's starting date with the current date to set some images in the cell
    NSComparisonResult startCompare = [[self.hH[indexPath.row] objectForKey:@"startDate"] compare: [NSDate date]];
    if (startCompare == NSOrderedDescending) {
        cell.quad.image = [UIImage imageNamed:@"no_HT"];
        cell.lblStartTime.textColor = [UIColor redColor];
    } else {
        cell.quad.image = [UIImage imageNamed:@"yes_HT"];
        cell.lblStartTime.textColor = [UIColor colorWithRed:104.0/255.0 green:166.0/255.0 blue:66.0/255.0 alpha:1.0];
    }
    NSString *dataInizio = [NSString stringWithFormat:@"%@ %@ %@ %@", self.dal, [self.formatterData stringFromDate:[self.hH[indexPath.row] objectForKey:@"startDate"]], self.ore, [self.formatterOra stringFromDate:[self.hH[indexPath.row] objectForKey:@"endDate"]]];
    cell.lblStartTime.text = dataInizio;
    PFObject *cat = [self.hH[indexPath.row] objectForKey:@"catParent"];
    NSString *languageCode = [[NSLocale preferredLanguages] objectAtIndex:0];
    if ([languageCode isEqualToString:@"it"]) {
        cell.lblCategory.text = [cat objectForKey:@"nome_it"];
    } else if ([languageCode isEqualToString:@"es"]) {
        cell.lblCategory.text = [cat objectForKey:@"nome_es"];
    } else {
        cell.lblCategory.text = [cat objectForKey:@"nome_en"];
    }

    //getting the image data from the Parse PFFile
    PFFile *theImage = [self.hH[indexPath.row] objectForKey:@"photo"];
    [theImage getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
        if (!error) {
            cell.cellImageView.image = [UIImage imageWithData:data];
        }
    }];

    //getting the cell object's owner and his profile
    PFUser *usr = [self.hH[indexPath.row] objectForKey:@"parent"];
    PFQuery *prof = [PFQuery queryWithClassName:@"Profile"];
    prof.cachePolicy = kPFCachePolicyCacheThenNetwork;
    [prof whereKey:@"parent" equalTo:usr];
    [prof getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
        if (!error) {
            //getting the object's rating and the number of votes
            PFQuery *rateQuery = [PFQuery queryWithClassName:@"Rating"];
            [rateQuery whereKey:@"parent" equalTo:object];
            [rateQuery getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
                if (!error) {
                    float vote = [[object objectForKey:@"rate"] floatValue];
                    float temp = ((vote * 2) + 0.5);
                    int tempvote = (int)temp;
                    float roundedVote = (float)tempvote / 2;
                    // drawing the stars number, depending on the rating obtained
                    UIImage *starsImage = [UIImage imageNamed:@"stars"];
                    UIGraphicsBeginImageContextWithOptions(cell.imgVoto.frame.size, NO, 0);
                    CGPoint starPoint = (CGPoint) {
                        .y = (cell.imgVoto.frame.size.height * (2 * roundedVote + 1)) - (starsImage.size.height)
                    };
                    [starsImage drawAtPoint:starPoint];
                    cell.imgVoto.image = UIGraphicsGetImageFromCurrentImageContext();
                    UIGraphicsEndImageContext();
                    cell.lblVoto.text = [NSString stringWithFormat:@"(%d)", [[object objectForKey:@"voters"] intValue]];
                }
            }];
        }
       }];
    return cell;
}

编辑:这是单元格代码:

+ (void)initialize {
    if (self != [HH class]) {
        return;
    }
}

-(id)initWithCoder:(NSCoder *)aDecoder {
    if ( !(self = [super initWithCoder:aDecoder]) ) return nil;

    self.cellImageView.image = [UIImage imageNamed:@"icona_foto"];
    self.cellImageView.contentMode = UIViewContentModeScaleToFill;
    self.formatterData = [[NSDateFormatter alloc] init];
    self.formatData = [[NSString alloc] init];
    self.formatterOra = [[NSDateFormatter alloc] init];
    self.formatOra = [[NSString alloc] init];
    self.formatData = [NSDateFormatter dateFormatFromTemplate:@"dd/MM" options:0 locale:[NSLocale currentLocale]];
    [self.formatterData setDateFormat:self.formatData];
    self.formatOra = [NSDateFormatter dateFormatFromTemplate:@"j:mm" options:0 locale:[NSLocale currentLocale]];
    [self.formatterOra setDateFormat:self.formatOra];
    self.lblVoto.text = @"(0)";

    return self;
}

第二次编辑:这是 viewDidLoad 方法中的代码:

        PFQuery *hours = [PFQuery queryWithClassName:@"HH"];
        hours.cachePolicy = kPFCachePolicyCacheThenNetwork;
        // here I'm making lots of query constraints that I'll not include

        [hours findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (!error) {
                self.objectsNumber = objects.count;
                self.hH = [[NSArray alloc] initWithArray:objects];
            }
        }];
        [self.tableView reloadData];
}

最佳答案

我会尽可能多地从 cellForRowAtIndexPath: 中移出逻辑,它需要非常轻量级才能获得良好的滚动性能。你在主线程上做了很多工作,当你从 Parse 中取回你的模型对象时,我会做更多的工作(如果你可以发布 viewDidLoad 我可以给你更多具体帮助)并在这些调用完成后更新 TableView :

  • [UIImage imageWithData:data]
  • NSDateFormatter 有关的任何事情
  • CLLocationinitWithLatitude:longitude:
  • 创建评分星级图片

这些都不依赖于 TableView 的状态,因此它们可以有效地预先计算并缓存在模型对象中。如果您只是简单地上下滚动表格,您将一遍又一遍地做所有相同的工作,从而影响您的表现。


针对提问者的最新代码进行了更新:

我不会在这里包含您的所有功能,但这应该会给您一个想法:

// create a single shared formatter instead of one per object
NSDateFormatter *dateFormatter = [NSDateFormatter dateFormatFromTemplate:@"dd/MM" options:0 locale:[NSLocale currentLocale]];
NSDateFormatter *timeFormatter = [NSDateFormatter dateFormatFromTemplate:@"j:mm" options:0 locale:[NSLocale currentLocale]];

[hours findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        self.objectsNumber = objects.count;

        for (SomeObject *modelObj in objects) {
             // if you can add properties to your model object directly, do that
             // otherwise write a category on the Parse object to add the ones you need
             modelObj.dateString = [NSString stringWithFormat:@"%@ %@ %@ %@", modelObj.dal, [self.dateFormatter stringFromDate:[modelObj objectForKey:@"startDate"]], modelObj.ore, [self.timeFormatter stringFromDate:[modelObj objectForKey:@"endDate"]]];

             // create your locations, images, etc in here too
        }

        self.hH = [[NSArray alloc] initWithArray:objects];
    }
}];]

然后在 cellForRowAtIndexPath: 中,获取预先计算的属性并将它们简单地分配给适当的标签、 ImageView 等。

通过 GCD 在主线程之外完成大部分处理会更好,但这很可能超出了这个问题的范围。参见 Using GCD and Blocks Effectively想要查询更多的信息。请记住,只从主线程与 UIKit 交互!

关于ios - 具有复杂单元格的 UITableView 缓慢且滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16375760/

有关ios - 具有复杂单元格的 UITableView 缓慢且滞后的更多相关文章

  1. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  2. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  3. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  4. ruby-on-rails - Rails 3.1 中具有相同形式的多个模型? - 2

    我正在使用Rails3.1并在一个论坛上工作。我有一个名为Topic的模型,每个模型都有许多Post。当用户创建新主题时,他们也应该创建第一个Post。但是,我不确定如何以相同的形式执行此操作。这是我的代码:classTopic:destroyaccepts_nested_attributes_for:postsvalidates_presence_of:titleendclassPost...但这似乎不起作用。有什么想法吗?谢谢! 最佳答案 @Pablo的回答似乎有你需要的一切。但更具体地说...首先改变你View中的这一行对此#

  5. ruby-on-rails - Prawn - 表格单元格内的链接 - 2

    我正在尝试用Prawn生成PDF。在我的PDF模板中,我有带单元格的表格。在其中一个单元格中,我有一个电子邮件地址:cell_email=pdf.make_cell(:content=>booking.user_email,:border_width=>0)我想让电子邮件链接到“mailto”链接。我知道我可以这样链接:pdf.formatted_text([{:text=>booking.user_email,:link=>"mailto:#{booking.user_email}"}])但是将这两行组合起来(将格式化文本作为内容)不起作用:cell_email=pdf.make_c

  6. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  7. ruby - 具有两个参数的 block - 2

    我从用户Hirolau那里找到了这段代码:defsum_to_n?(a,n)a.combination(2).find{|x,y|x+y==n}enda=[1,2,3,4,5]sum_to_n?(a,9)#=>[4,5]sum_to_n?(a,11)#=>nil我如何知道何时可以将两个参数发送到预定义方法(如find)?我不清楚,因为有时它不起作用。这是重新定义的东西吗? 最佳答案 如果您查看Enumerable#find的文档,您会发现它只接受一个block参数。您可以将它发送两次的原因是因为Ruby可以方便地让您根据它的“并行赋

  8. ruby-on-rails - 在 RSpec 中,如何以任意顺序期望具有不同参数的多条消息? - 2

    RSpec似乎按顺序匹配方法接收的消息。我不确定如何使以下代码工作:allow(a).toreceive(:f)expect(a).toreceive(:f).with(2)a.f(1)a.f(2)a.f(3)我问的原因是a.f的一些调用是由我的代码的上层控制的,所以我不能对这些方法调用添加期望。 最佳答案 RSpecspy是测试这种情况的一种方式。要监视一个方法,用allowstub,除了方法名称之外没有任何约束,调用该方法,然后expect确切的方法调用。例如:allow(a).toreceive(:f)a.f(2)a.f(1)

  9. ruby - 使用 AES 的 Rails 加密,过于复杂 - 2

    我在加密来self正在使用的第三方供应商的值时遇到问题。他们的指令如下:1)Converttheencryptionpasswordtoabytearray.2)Convertthevaluetobeencryptedtoabytearray.3)Theentirelengthofthearrayisinsertedasthefirstfourbytesontothefrontofthefirstblockoftheresultantbytearraybeforeencryption.4)EncryptthevalueusingAESwith:1.256-bitkeysize,2.25

  10. ruby - 单元测试文件 I/O 方法 - 2

    我对单元测试还是比较陌生。我用Ruby编写了一个类,它接受一个文件,在该文件中搜索给定的Regex模式,替换它,然后将更改保存回文件。我希望能够为此方法编写单元测试,但我不知道我将如何去做。有人能告诉我我们如何对处理文件i/o的方法进行单元测试吗? 最佳答案 看看这个HowdoIunit-testsavingfiletothedisk?基本上这个想法是一样的,文件系统是你的类的依赖。所以引入一个可以在你的单元测试中模拟的角色/接口(interface)(这样你在单元测试时就没有依赖性);角色中的方法应该是您从文件系统中需要的所有东西

随机推荐