使用新数据快速更新 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 的相关文章

  • Xcode 6.4 Swift 单元测试无法编译:“GPUImage.h 未找到”“无法导入桥接标头”

    我的 Xcode 项目构建并运行良好 它有 Swift 和 Objective C 代码 它已安装 GPUImage 我向它添加了单元测试 现在它将不再编译 找不到 GPUImage h 文件 导入桥接标头失败 以下是我发现并尝试过的解决方
  • 从基元创建自定义形状

    我正在尝试通过组合原始形状来创建自定义物理形状 目标是创建一个圆形立方体 合适的方法似乎是初始化 形状 变换 我在这里找到的https developer apple com library prerelease ios documenta
  • Swift - 在 TableView 单元格中使用步进器递增标签

    这里又是一个 Swift 初学者 我只是想在每个 TableView 单元格中使用一个步进器来增加同一单元格中的标签 我发现了关于这个主题的几个问题 但它们包含其他元素 我无法提取基本概念 Swift Stepper Action 更改同一
  • 在 iOS 8 中创建通话/双高状态栏?

    是否有调用自定义通话 双高状态栏的标准方法 如果没有 那么构建我自己的功能的最佳起点是哪里 我知道关于如何做到这一点存在一些多年的问题 但没有任何令人满意的答案 有什么新方法可以做到这一点吗 可能在 iOS 8 中 这里没有什么新鲜事 但我
  • 使用 iPhone 控制蓝牙音频设备

    我正在寻找为 iPhone 编写应用程序 它将能够控制汽车中的收音机和 CD 播放器 收音机和播放器具有可用的蓝牙连接 我开始这个问题是为了获得这个地方所需的所有信息 我有几个问题 但如果您发现任何我没有要求的对我开始开发此应用程序不重要的
  • Apple 针对 http 直播流媒体应用程序的政策

    这里有要求 http developer apple com library ios documentation NetworkingInternet Conceptual StreamingMediaGuide UsingHTTPLive
  • 如何通过我的 ios 应用程序的指示打开苹果地图应用程序

    我的目标是从 ios 应用程序打开带有方向的地图应用程序 我可以打开地图应用程序 但它没有显示方向 我编写的代码如下 NSString mystr NSString alloc initWithFormat http maps apple
  • Cordova - 启动后出现白屏,控制台中没有例外

    我已经离开我的 Cordova 应用程序一段时间了 但昨天刚刚进行了一次新的克隆 发现它出现了 死机白屏 症状 启动画面显示 程序加载 然后我就得到一个空白屏幕 更多细节 CLI 科尔多瓦 6 1 1 安卓 5 1 1 ios 4 1 1
  • Swift 3 中数组的 indexOf(_:) 方法的替换

    在我的项目 用 Swift 3 编写 中 我想使用从数组中检索元素的索引indexOf 方法 存在于 Swift 2 2 中 但我找不到任何替代方法 Swift 3 中是否有任何好的替代方法或类似的方法 Update 我忘记提及我想在自定义
  • 如何将 CIFilter 输出到相机视图?

    我刚刚开始使用 Objective C 我正在尝试创建一个简单的应用程序 它显示带有模糊效果的相机视图 我得到了与 AVFoundation 框架一起使用的相机输出 现在 我正在尝试连接 Core 图像框架 但不知道如何连接 Apple 文
  • ExpandableLabel iOS 中的“少看”

    我正在使用第三方库可扩展标签 https github com apploft ExpandableLabel实施一个see more特征 我正在寻找仅快速的解决方案 其中包含标签中的文本而不是按钮中的文本 因此这可以完美地工作 添加库并更
  • iOS JPEG 图像旋转 90 度

    我正在使用选择器视图从相册中选择图像 我使用上面的代码 void imagePickerController UIImagePickerController picker didFinishPickingMediaWithInfo NSDi
  • Excel 工作表到 iPhone 数据 -- A 点到 B 点

    尽可能简单 我有一个非常简单的 Excel 电子表格 只有 1000 多条记录 我想将其用作 iPhone 应用程序的静态数据源 最好的进攻计划是什么 我心中的可能性 1 直接读取XLS作为数据源 是否有Obj C库用于此 2 将XLS 转
  • CIAdditionCompositing 给出不正确的效果

    我正在尝试通过平均其他几个图像来创建图像 为了实现这一点 我首先将每个图像变暗 其系数等于我平均的图像数量 func darkenImage by multiplier CGFloat gt CIImage let divImage CII
  • Xamarin.Forms DataTemplateSelector 不适用于 iOS(未调用构造函数)

    我正在膨胀数据模板选择器 如下所示
  • GoogleSignIn ios 附加到谷歌表格

    我目前正在开发一个 iOS 应用程序 该应用程序需要写入登录用户拥有的 Google 工作表 要登录我正在使用的用户GoogleSignInpod 并附加到我正在使用的谷歌表GoogleAPIClientForREST Sheets pod
  • Cocoa 基于文档的应用程序中的 MVC

    我目前正在对我的应用程序进行重构和重组 我意识到模型和视图及其控制器之间的一些分离已经减少 我希望进行一些清理 我的应用程序中使用了几个关键类 NSPersistentDocument NSWindowController 和模型类 NSP
  • ArraySlice 中的 Swift [重复]

    这个问题在这里已经有答案了 在数组上使用 prefix 方法后 我得到了所谓的 arraySlice 我怎样才能将其转换为数组 我试图从 FacebookGraphApi 获取 Ints 然后请求前 3 个 前缀 3 并尝试将它们添加到新数
  • 弱变量中间为零

    弱变量什么时候变为零 weak var backgroundNode SKSpriteNode texture SKTexture image initialBackgroundImage backgroundNode position C
  • Swift 中的 quitFirstResponder

    我怎样才能用Apple的新语言实现它 Objective C 代码 void touchesBegan NSSet touches withEvent UIEvent event for UIView view in self view s

随机推荐

  • 如何知道何时使用 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