使用新数据快速更新 UITableView

2024-04-29

我正在尝试重新填充我的UITableView来自另一个 JSON 调用的数据。

然而,我当前的设置似乎不起作用,虽然有很多相同的问题,但我可以找到我已经尝试过的答案。

我将 API 数据保存在CoreData实体对象。我用我的 UITableView 填充CoreData实体。

在我当前的设置中,我有 3 个不同的 API 调用,它们具有不同的数据量,当然还有不同的值。我需要能够在这 3 个数据集之间切换,这就是我现在正在努力实现的目标。 (到目前为止还没有进展)。

我有一个名为“loadSuggestions”的函数,我认为这是我的错误所在。

  • 首先我检查互联网连接。

  • 我设置了 ManagedObjectContext

  • 我检查需要调用什么 API(这是在调用函数之前确定的,并且我检查了它是否按预期工作)

  • 我从它尝试调用的实体中删除所有当前数据。 (我也尝试从最后的数据中删除数据UITableView已加载。这并没有改变任何事情)。我还检查了这是否有效。删除数据后,我检查它是否打印出一个空数组,我还尝试记录它删除的对象以确保。

  • 然后我获取新数据,将其保存到临时变量中。然后将其保存到我的核心数据中。

  • 然后,我进行第二次 API 调用(取决于第一个 API 的变量),获取该数据并以相同的方式保存它。

  • 我将对象附加到数组中UITableView填充它的细胞。 (我检查了它打印是否正确)

  • 最后我重新加载 tableView。 (不会改变任何事情)

这是函数:

func loadSuggestions() {
    println("----- Loading Data -----")
    // Check for an internet connection.
    if Reachability.isConnectedToNetwork() == false {
        println("ERROR: -> No Internet Connection <-")
    } else {
        // Set the managedContext again.
        managedContext = appDelegate.managedObjectContext!

        // Check what API to get the data from
        if Formula == 0 {
            formulaEntity = "TrialFormulaStock"
            println("Setting Entity: \(formulaEntity)")
            formulaAPI = NSURL(string: "http://api.com/json/entry_weekly.json")
        } else if Formula == 1 {
            formulaEntity = "ProFormulaStock"
            println("Setting Entity: \(formulaEntity)")
            formulaAPI = NSURL(string: "http://api.com/json/entry_weekly.json")
        } else if Formula == 2 {
            formulaEntity = "PremiumFormulaStock"
            formulaAPI = NSURL(string: "http://api.com/json/proff_weekly.json")
            println("Setting Entity: \(formulaEntity)")
        } else if Formula == 3 {
            formulaEntity = "PlatinumFormulaStock"
            println("Setting Entity: \(formulaEntity)")
            formulaAPI = NSURL(string: "http://api.com/json/fund_weekly.json")
        }

        // Delete all the current objects in the dataset
        let fetchRequest = NSFetchRequest(entityName: formulaEntity)
        let a = managedContext.executeFetchRequest(fetchRequest, error: nil) as! [NSManagedObject]
        for mo in a {
            managedContext.deleteObject(mo)
        }

        // Removing them from the array
        stocks.removeAll(keepCapacity: false)
        // Saving the now empty context.
        managedContext.save(nil)

        // Set up a fetch request for the API data
        let entity =  NSEntityDescription.entityForName(formulaEntity, inManagedObjectContext:managedContext)
        var request = NSURLRequest(URL: formulaAPI!)
        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
        var formula = JSON(data: data!)

        // Loop through the api data.
        for (index: String, actionable: JSON) in formula["actionable"] {

            // Save the data into temporary variables
            stockName = actionable["name"].stringValue
            ticker = actionable["ticker"].stringValue
            action = actionable["action"].stringValue
            suggestedPrice = actionable["suggested_price"].floatValue
            weight = actionable["percentage_weight"].floatValue

            // Set up CoreData for inserting a new object.
            let stock = NSManagedObject(entity: entity!,insertIntoManagedObjectContext:managedContext)

            // Save the temporary variables into coreData
            stock.setValue(stockName, forKey: "name")
            stock.setValue(ticker, forKey: "ticker")
            stock.setValue(action, forKey: "action")
            stock.setValue(suggestedPrice, forKey: "suggestedPrice")
            stock.setValue(weight, forKey: "weight")

            // Get ready for second API call.
            var quoteAPI = NSURL(string: "http://dev.markitondemand.com/Api/v2/Quote/json?symbol=\(ticker)")

            // Second API fetch.
            var quoteRequest = NSURLRequest(URL: quoteAPI!)
            var quoteData = NSURLConnection.sendSynchronousRequest(quoteRequest, returningResponse: nil, error: nil)
            if quoteData != nil {
                // Save the data from second API call to temporary variables
                var quote = JSON(data: quoteData!)
                betterStockName = quote["Name"].stringValue
                lastPrice = quote["LastPrice"].floatValue

                // The second API call doesn't always find something, so checking if it exists is important.
                if betterStockName != "" {
                    stock.setValue(betterStockName, forKey: "name")
                }

                // This can simply be set, because it will be 0 if not found.
                stock.setValue(lastPrice, forKey: "lastPrice")

            } else {
                println("ERROR ----------------- NO DATA for \(ticker) --------------")
            }

            // Error handling
            var error: NSError?
            if !managedContext.save(&error) {
                println("Could not save \(error), \(error?.userInfo)")
            }
            // Append the object to the array. Which fills the UITableView
            stocks.append(stock)

        }

        // Reload the tableview with the new data.
        self.tableView.reloadData()
    }
}

目前,当我推送到这个 viewController 时,这个函数被调用viewDidAppear像这样:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)

    tableView.allowsSelection = true
    if isFirstTime {
        loadSuggestions()
        isFirstTime = false
    }
}

它正确填充了 tableView,一切似乎都按计划进行。

但是,如果我打开滑出式菜单并调用函数来加载不同的数据,则不会发生任何情况,这是一个示例函数:

func platinumFormulaTapGesture() {
    // Menu related actions
    selectView(platinumFormulaView)
    selectedMenuItem = 2
    // Setting the data to load
    Formula = 3
    // Sets the viewController. (this will mostly be the same ViewController)
    menuTabBarController.selectedIndex = 0
    // Set the new title
    navigationController?.navigationBar.topItem!.title = "PLATINUM FORMULA"
    // And here I call the loadSuggestions function again. (this does run)
    SuggestionsViewController().loadSuggestions()
}

这是 2 个相关的 tableView 函数:

行数:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return stocks.count
}

和 cellForRowAtIndexPath(这是我使用 CoreData 设置单元格的位置)

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("com.mySuggestionsCell", forIndexPath: indexPath) as! mySuggestionsCell

    let formulaStock = stocks[indexPath.row]
    cell.stockNameLabel.text = formulaStock.valueForKey("name") as! String!
    cell.tickerLabel.text = formulaStock.valueForKey("ticker") as! String!
    action = formulaStock.valueForKey("action") as! String!
    suggestedPrice = formulaStock.valueForKey("suggestedPrice") as! Float

    let suggestedPriceString = "Suggested Price\n$\(suggestedPrice.roundTo(2))" as NSString
    var suggestedAttributedString = NSMutableAttributedString(string: suggestedPriceString as String)

    suggestedAttributedString.addAttributes(GrayLatoRegularAttribute, range: suggestedPriceString.rangeOfString("Suggested Price\n"))
    suggestedAttributedString.addAttributes(BlueHalisRBoldAttribute, range: suggestedPriceString.rangeOfString("$\(suggestedPrice.roundTo(2))"))
    cell.suggestedPriceLabel.attributedText = suggestedAttributedString

    if action == "SELL" {
        cell.suggestionContainer.backgroundColor = UIColor.formulaGreenColor()
    }

    if let lastPrice = formulaStock.valueForKey("lastPrice") as? Float {
        var lastPriceString = "Last Price\n$\(lastPrice.roundTo(2))" as NSString
        var lastAttributedString = NSMutableAttributedString(string: lastPriceString as String)

        lastAttributedString.addAttributes(GrayLatoRegularAttribute, range: lastPriceString.rangeOfString("Last Price\n"))

        percentDifference = ((lastPrice/suggestedPrice)*100.00)-100

        if percentDifference > 0 && action == "BUY" {
            lastAttributedString.addAttributes(RedHalisRBoldAttribute, range: lastPriceString.rangeOfString("$\(lastPrice.roundTo(2))"))
        } else if percentDifference <= 0 && percentDifference > -100 && action == "BUY" {
            lastAttributedString.addAttributes(GreenHalisRBoldAttribute, range: lastPriceString.rangeOfString("$\(lastPrice.roundTo(2))"))
        } else if percentDifference <= 0 && percentDifference > -100 && action == "SELL" {
            lastAttributedString.addAttributes(RedHalisRBoldAttribute, range: lastPriceString.rangeOfString("$\(lastPrice.roundTo(2))"))
        } else if percentDifference == -100 {
            lastPriceString = "Last Price\nN/A" as NSString
            lastAttributedString = NSMutableAttributedString(string: lastPriceString as String)

            lastAttributedString.addAttributes(GrayLatoRegularAttribute, range: lastPriceString.rangeOfString("Last Price\n"))
            lastAttributedString.addAttributes(BlackHalisRBoldAttribute, range: lastPriceString.rangeOfString("N/A"))
        }

        cell.lastPriceLabel.attributedText = lastAttributedString
    } else {
        println("lastPrice nil")
    }

    weight = formulaStock.valueForKey("weight") as! Float
    cell.circleChart.percentFill = weight
    let circleChartString = "\(weight.roundTo(2))%\nWEIGHT" as NSString
    var circleChartAttributedString = NSMutableAttributedString(string: circleChartString as String)
    circleChartAttributedString.addAttributes(BlueMediumHalisRBoldAttribute, range: circleChartString.rangeOfString("\(weight.roundTo(2))%\n"))
    circleChartAttributedString.addAttributes(BlackSmallHalisRBoldAttribute, range: circleChartString.rangeOfString("WEIGHT"))
    cell.circleChartLabel.attributedText = circleChartAttributedString

    cell.selectionStyle = UITableViewCellSelectionStyle.None
    return cell
}

我将 appDelegate 定义为类中的第一件事:

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var managedContext = NSManagedObjectContext()

我认为这就是可能导致该错误的所有代码。我再次认为最可能的原因是loadSuggestions功能。

为了强制更新 tableView 我也尝试调用setNeedsDisplay and setNeedsLayout都在self.view and tableView,这两者似乎都没有做任何事情。

任何弄清楚为什么这个 tableView 拒绝更新的建议都会有巨大的帮助!

我对代码之墙表示歉意,但我一直无法找到问题的确切根源。


PlatinumFormulaTapGesture 函数中的这一行不正确,

SuggestionsViewController().loadSuggestions()

这将创建 SuggestionsViewController 的一个新实例,该实例不是您在屏幕上显示的实例。您需要获得一个指向您所拥有的指针。你如何做到这一点取决于你的控制器层次结构,你还没有充分解释它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用新数据快速更新 UITableView 的相关文章

  • 无法构建 Saurik 的 ldid 实用程序

    当我执行此命令 make sh 时 我遇到这些错误 构建用于越狱调整开发的 ldid 实用程序 Bilals Mac ldid billy make sh g arch i386 arch x86 64 arch ppc arch armv
  • 如何打开定位服务

    当有人第一次拒绝时 如何从实际应用程序重新打开定位服务 我可以选择关闭或打开它 您只能提示他们在屏幕上打开定位服务 如下所示 UIApplication sharedApplication openURL NSURL URLWithStri
  • 如何替换已弃用的方法dispatch_get_current_queue()? [复制]

    这个问题在这里已经有答案了 我正在 iOS 5 中使用 xmppframework 开发一个聊天应用程序 它工作得很好 但我将 Xcode 更新到 4 5 1 将 iOS 5 更新到 iOS 6 将 Mac OS 更新到 10 7 5 但由
  • 如何在 SwiftUI 中仅使用 ForEach 而不是列表来滑动删除

    我正在 SwiftUI 中使用 ForEach 制作自定义列表 我的目标是进行滑动删除手势 而不是将 ForEach 嵌入到列表中 到目前为止 这是我的代码 import SwiftUI struct ContentView View le
  • 如何在 Core Data 中存储图像?

    只是猜测 我创建一个属性并将其类型设置为 二进制 但最终我该如何使用它呢 我猜幕后有一个 NSData 那么该属性实际上采用 NSData 吗 这个问题已经被问过很多次了 答案有点复杂 当涉及二进制数据时 您应该根据要使用的数据的预期大小来
  • 如何在 Firebase 控制台中使用 Apple 新的 APN .p8 证书

    随着最近 Apple 开发者帐户的升级 我面临着一个困难 在尝试创建推送通知证书时 它为我提供了 p8 证书 而不是可以导出到 p12 的 APNs 证书 Firebase 控制台仅接受 p12 证书 那么我如何从这些新的 p8 证书中获取
  • 在没有预览窗口的情况下使用 AVCaptureVideoDataOutputSampleBufferDelegate

    我正在开发一个基于 Swift 的 macOS 应用程序 我需要捕获视频输入 但不将其显示在屏幕上 而不是显示视频 我想将缓冲的数据发送到其他地方进行处理 并最终显示它在 a 中的一个物体上SceneKit scene 我有一个Camera
  • 在 WKWebView 中禁用放大手势

    我正在寻找一种方法来禁用 WKWebView 的 iOS 实现上的 捏合缩放 放大手势 OS X 有一个 magnification BOOL 属性 但在 iOS 上似乎不可用 WKWebView h if TARGET OS IPHONE
  • 如何在 iOS 9 上可靠地检测是否连接了外部键盘?

    在 iOS 9 之前 确定是否连接外部键盘的最可靠方法是监听UIKeyboardWillShowNotification并使文本字段成为第一响应者 如中所述这个问题 https stackoverflow com questions 289
  • 使用完成处理程序在 Swift 中调用连续动画

    我正在制作一个可以显示化学反应动画的应用程序 每个原子都是一个 SCNSphere 并通过 SCNActions 进行动画处理 我尝试使用 runAction 中的完成处理程序在当前操作完成后调用下一个动画 因为每个原子必须做出很多不同的运
  • 带操作按钮的颤动本地通知

    我在我的 flutter 项目中尝试了 flutter 本地通知插件 它在简单通知上工作正常 但我需要带有操作按钮的通知功能 请帮助我或建议我实现此功能 不幸的是 flutter local notifications 插件尚不支持操作按钮
  • 在 Xcode 5 中重命名 iOS 项目[重复]

    这个问题在这里已经有答案了 我需要重命名一个 iOS 项目 有没有办法在不开始一个全新项目的情况下做到这一点 我发现的所有其他信息都与 Xcode 4 或旧版本相关 这些方法似乎使项目崩溃 我在尝试任何名称更改之前创建了一个快照 在 Xco
  • 如何接收有关与我共享的记录中所做更改的 CloudKit 通知?

    我有两个 iCloud 帐户 A and B 在两个不同的设备上 来自其中之一 A 我将 ckrecord 分享给另一个人 B 像这样 let controller UICloudSharingController controller p
  • UIButton的高亮状态由什么控制事件开始和结束

    我正在创建类似钢琴的视图UIButton作为钢琴键 什么UIControlEvents当按钮获得和失去突出显示状态时 我应该监听以获得回调吗 我试图创建子类UIButton并添加属性观察者highlighted并且运行良好 然而 有时我需要
  • Apple Watch 预构建操作可更改故事板 customModule 引用

    我目前有一个项目 其中包含同一应用程序的 3 个不同版本 不同的品牌等 该项目运行得很好 从那时起 我添加了 3 个新的 Apple Watch 目标 每个应用程序 版本 1 个 其中 2 个引用 主 Apple Watch 目标中的文件
  • 在 iOS 中,如何创建一个始终位于所有其他视图控制器之上的按钮?

    无论是否呈现模态或用户执行任何类型的转场 有没有办法让按钮在整个应用程序中 始终位于顶部 而不是屏幕顶部 有什么方法可以让这个按钮可拖动并可捕捉到屏幕上吗 我正在以苹果自己的辅助触摸作为此类按钮的示例 您可以通过创建自己的子类来做到这一点U
  • UIImageJPEGRepresentation 在视网膜显示屏上提供 2x 图像

    我有这段代码 它创建一个图像 然后向其添加一些效果并缩小其大小以使其largeThumbnail UIImage originalImage UIImage imageWithData self originalImage thumbnai
  • 什么是 WKWebView 中的 WKErrorDomain 错误 4

    fatal error LPWebView encounters an error Error Domain WKErrorDomain Code 4 A JavaScript exception occurred UserInfo 0x7
  • Swift 中的 import 语句是否有相关成本?

    阅读字符串宣言 我看到一个段落 https github com apple swift blob master docs StringManifesto md batteries included关于避免Foundation不需要的时候导
  • UIView晃动动画

    我试图在按下按钮时使 UIView 摇动 我正在调整我找到的代码http www cimgf com 2008 02 27 core animation tutorial window shake effect http www cimgf

随机推荐

  • 如何知道何时使用 XML 解析器以及何时使用 ActiveResource?

    我尝试使用 ActiveResource 来解析更像 HTML 文档的 Web 服务 但一直收到 404 错误 我是否需要使用 XML 解析器来完成此任务而不是 ActiveResource 我的猜测是 只有当您使用来自另一个 Rails
  • 什么是好的、免费的 PHP 图表套件?

    我要做的只是基本的折线图 任何人分享的经验将不胜感激 不是真正的 PHP 但我发现 amchart 非常容易实现 而且看起来很棒 http www amcharts com http www amcharts com 还可以查看 Googl
  • 证书吊销如何与中间 CA 配合使用?

    假设 PKI 层次结构如下所示 root CA gt inter 1 CA gt user 1 gt inter 2 CA gt user 2 我的问题是 根 CA 是否还需要定期从其子项 inter 1 和 inter 2 下载 CRL
  • NodeJS 最佳实践:流量控制错误?

    在 Node js 中 我应该使用错误来进行流程控制 还是应该更像异常一样使用它们 我正在 Sails js 中编写一个身份验证控制器和一些单元测试 目前 我的注册方法检查是否存在具有相同用户名的用户 如果用户已存在并具有该用户名 我的模型
  • Ionic 3 Uncaught(承诺):[object Object]

    我是 Ionic 3 和移动开发的新手 我正在尝试将 MySQL DB 连接到我的 Ionic 应用程序和 PHP Restful API 我用 Postman 测试了 API 它工作得很好 为了在 Ionic 中实现它 我做了以下操作 我
  • 具有 BLoC 模式的 BottomNavigationBar

    我真的很喜欢 BLoC 模式 并且正在尝试理解它 但我似乎无法弄清楚它应该如何应用BottomNavigationBar 制作导航页面列表并在导航栏点击事件上设置当前索引会导致整个应用程序重绘 因为setState 我可以使用Navigat
  • Java 8 列表到带有总和的 EnumMap

    我有以下课程 public class Mark private Long id private Student student private Integer value 0 private Subject subject public
  • 如何在 swagger 规范中表示十进制浮点数?

    我想在我的 api 文档中用 2 位小数表示小数点 用 1 位小数表示 我正在使用 swagger 2 0 规范中是否有内置定义的类型或任何其他 圆形 参数 或者我唯一的选择是使用 x 扩展 OpenAPI fka Swagger 规范使用
  • Magento - 分页生成错误的 URL

    除了网址之外 我的分页工作正常 第 2 页的链接是 example com products 21p 2 什么时候应该是 example com products p 2 当我在地址栏中输入后者时 它工作正常 这是生成链接的代码 li a
  • 使用 jQuery 中止 Ajax 请求

    是否有可能使用 jQuery 我取消 中止 Ajax 请求我还没有收到回复 大多数 jQuery Ajax 方法都会返回 XMLHttpRequest 或等效的 对象 因此您可以使用abort 请参阅文档 中止方法 http msdn mi
  • 适用于 Windows 的 C++11 编译器

    我刚刚在 Channel9 上看了一些视频 我发现 lambda 之类的东西真的很酷 当我尝试复制该示例时 它失败了 auto也没用 我正在使用诺基亚的 qtcreator 它随 gcc 4 4 0 一起提供 我想知道哪个编译器实现了有趣的
  • 尝试在类中定义静态常量变量

    我正在定义一个变量adc cmd 9 as a static const unsigned char在我的课堂上ADC私人之下 由于它是一个常量 我想我只需在它自己的类中定义它 但这显然不起作用 pragma once class ADC
  • 使用 for_each 调用成员函数

    这是我原来的代码 include stdafx h include
  • 在 AS3 中将 Little-endian ByteArray 转换为 Big-endian

    AS3中如何将Little endian ByteArray转换为Big endian 我将 bitmapData 转换为 Big endian ByteArray 然后使用 Adob e Alchemy 将其推入内存 然后当我从内存中读取
  • IEnumerable / IQueryable 上的动态 LINQ OrderBy

    我在中找到了一个例子VS2008示例 http msdn2 microsoft com en us bb330936 aspx用于动态 LINQ 允许您使用类似 SQL 的字符串 例如OrderBy Name Age DESC 用于订购 不
  • “sites-enabled”和“sites-available”目录之间有什么区别? [关闭]

    Closed 这个问题是与编程或软件开发无关 help closed questions 目前不接受答案 Locked 这个问题及其答案是locked help locked posts因为这个问题是题外话 但却具有历史意义 目前不接受新的
  • PHP/Apache 中的输出缓冲块如何工作?

    假设我将随机数据从 PHP 回显到浏览器 随机数据总量约为 XGb 回显以 YKb 块的形式完成 不使用 ob start PHP 和 Apache 缓冲区已满后 echo 调用是否会阻塞 客户端无法以与生成数据相同的速度使用数据 如果是
  • ui.router 和 ui.state 之间的 angularJS 有什么区别?

    我正在努力使用多个视图来设置 angularJS SPA角度 ui 路由器 https github com angular ui ui router 当我浏览网络上的教程和操作方法时 我看到了各种各样的依赖项 ui router gith
  • 如何将向量标准化/非标准化到范围 [-1;1]

    我怎么能够正常化到范围的向量 1 1 我想使用函数norm 因为它会更快 也让我知道我该怎么做非规范化之后的向量正常化 norm对向量进行归一化 使其平方和为 1 如果要对向量进行归一化 使其所有元素都在 0 和 1 之间 则需要使用最小值
  • 使用新数据快速更新 UITableView

    我正在尝试重新填充我的UITableView来自另一个 JSON 调用的数据 然而 我当前的设置似乎不起作用 虽然有很多相同的问题 但我可以找到我已经尝试过的答案 我将 API 数据保存在CoreData实体对象 我用我的 UITableV