动态更改cell.update Date函数?

时间:2019-05-04 06:35:18

标签: ios swift uitableview date nsdate

我只是这一切的新手,所以请原谅我的无知!我有一个Table View,每次打开场景时都会调用它的单元格更新方法(按日期排序)。我试图根据对象上次编辑的时间动态显示不同的日期格式。示例:如果日期是今天,则显示时间;如果日期是昨天,则显示“昨天”。我的问题是-编写此代码的最佳方法是什么,在cell.update调用中调用以下func会占用大量内存?我该如何写得更好?任何帮助将不胜感激!

func update(with fitnessInfo: Fitness) {
    if let date = fitnessInfo.dateEdited as Date? {
        let today = Calendar.current.isDateInToday(date)
        let yesterdayFunc = Calendar.current.isDateInYesterday(date)
        let yesterday = date.addingTimeInterval(172800)
        let withinSevenDays = date.addingTimeInterval(604800)
        let dateFormatter = DateFormatter()

        func setdate(_ dateFormatter: DateFormatter) {
            let convertedDate = dateFormatter.string(from: date)
            fitnessDateLabel.text = convertedDate
        }
        if today == true {
            dateFormatter.dateFormat = "h:mm a"
            setdate(dateFormatter)
        } else if yesterdayFunc == true {
            fitnessDateLabel.text = "Yesterday"
        } else {
            switch date {
            case yesterday...withinSevenDays:
                dateFormatter.dateFormat = "EEEE"
                setdate(dateFormatter)
            default:
                dateFormatter.dateFormat = "MMMM dd, yyyy"
                setdate(dateFormatter)
            }
        }
    }

这里是调用它的Table View函数(cellForRowAt)。

tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: “fitnessCell", for: indexPath) as! FitnessTableViewCell
        let fitnessInfo = fetchedRC.object(at: indexPath)
        cell.update(with: fitnessInfo)
        return cell
    }

1 个答案:

答案 0 :(得分:0)

  1. 如果代码能正常工作,那就不错了。
  2. 在进行任何性能优化之前编写单元测试和性能测试是一个好主意。因此,您将看到所做的更改不会影响结果并改善性能。您还可以使用Xcode工具,通过单击Product-> Profile并选择Time profile and Allocations工具来了解您的代码如何精确地使用CPU和内存。不要忘记性能优化通常是内存和CPU使用率之间的折衷。
  3. 您应该将逻辑与表示法分开。这样您就可以编写单元测试。另外,您可以静态保留DateFrommater,而不是每次绘制单元格都将其初始化。这是一个如何完成的示例:

    final class DateMapper {
        static let todayDateFormatter = DateFormatter()
        static let lastWeekAgoDateFormatter = DateFormatter()
        static let moreThanWeekAgoDateFormatter = DateFormatter()
        let today: Date
        let currentCalendar = Calendar.current
    
        init(today: Date) {
            self.today = today
            DateMapper.todayDateFormatter.dateFormat = "h:mm a"
            DateMapper.lastWeekAgoDateFormatter.dateFormat = "EEEE"
            DateMapper.moreThanWeekAgoDateFormatter.dateFormat = "MMMM dd, yyyy"
        }
    
        func formattedDate(date: Date) -> String {
            guard let totalDays = currentCalendar.dateComponents([.day], from: date, to: today).day else {
                return ""
            }
            switch totalDays {
            case 0:
                return DateMapper.todayDateFormatter.string(from: date)
            case 1:
                return "Yesterday"
            case 2...7:
                return DateMapper.lastWeekAgoDateFormatter.string(from: date)
            default:
                return DateMapper.moreThanWeekAgoDateFormatter.string(from: date)
            }
        }
    }
    

此类可在您的更新方法中使用,如下所示:

  func update(with fitnessInfo: Fitness) {
       let dateMapper = DateMapper(today: Date())
       fitnessDateLabel.text = dateMapper.formattedDate(date: fitnessInfo.dateEdited)
   }

或者您可以在ViewController中保留DateMapper并直接在cellForRowAt上使用它。

  1. 此类可以用单元测试覆盖:

    class ExampleTests: XCTestCase {
    
        var dateMapper: DateMapper {
            let todayStub = dateStubByComponents(year: 2019, month: 5, day: 4, hour: 12)
            return DateMapper(today: todayStub)
        }
    
        func testTodayDate() {
            // arrange
            let todayStub = dateStubByComponents(year: 2019, month: 5, day: 4, hour: 11)
    
            // act
            let result = dateMapper.formattedDate(date: todayStub)
    
            // assert
            XCTAssertEqual(result, "11:00 AM")
        }
    
        func testYestadayDate() {
            // arrange
            let yesterdayStub = dateStubByComponents(year: 2019, month: 5, day: 3, hour: 0)
    
            // act
            let result = dateMapper.formattedDate(date: yesterdayStub)
    
            // assert
            XCTAssertEqual(result, "Yesterday")
        }
    
        func testLastWeekDate() {
            // arrange
            let lastWeekStub = dateStubByComponents(year: 2019, month: 5, day: 2, hour: 0)
    
            // act
            let result = dateMapper.formattedDate(date: lastWeekStub)
    
            // assert
            XCTAssertEqual(result, "Thursday")
        }
    
        func testPerformanceExample() {
            let lastWeekStub = dateStubByComponents(year: 2019, month: 5, day: 2, hour: 0)
            self.measure {
                 _ = dateMapper.formattedDate(date: lastWeekStub)
            }
        }
    
        // MARK: Private
    
        private func dateStubByComponents(year: Int, month: Int, day: Int, hour: Int) -> Date {
        var dateStubComponents = DateComponents()
        dateStubComponents.year = year
        dateStubComponents.month = month
        dateStubComponents.day = day
        dateStubComponents.hour = hour
    
        guard let dateStub = Calendar.current.date(from: dateStubComponents) else { fatalError("Date must be valid") }
           return dateStub
        }
    }
    

在控制台上,您将看到将Date转换为String所需的时间:

  

值:[0.000922、0.000063、0.000041、0.000038、0.000036、0.000035,   0.000035、0.000036、0.000043、0.000027]