ios - 从本地化字符串设置核心数据值

标签 ios core-data webkit

编辑:代码现在可以工作了,原来它是陈旧的数据。我保存并清理了项目,重置了模拟器,现在它可以工作了!感谢@pbasdf 帮助我!

我仍然习惯核心数据和本地化字符串,所以我不确定我是否错误地使用了本地化字符串,或者问题是否出在其他地方,但是当我点击单元格时,我可以通过我的打印声明所有值都是零,显然没有加载网页。

我正在使用 localized.strings 文件将名称等同于其相应的 URL:

"iPhone" = "http://www.apple.com/iphone/";
"iPad" = "http://www.apple.com/ipad/";
"Macbook" = "http://www.apple.com/macbook/";
"Google" = "https://www.google.com/";
"Firebase" = "https://firebase.google.com/";
"Magic Leap" = "https://www.magicleap.com/";
"Facebook" = "https://www.facebook.com/";
"Instagram" = "https://www.instagram.com/?hl=en";
"WhatsApp" = "https://www.whatsapp.com/";
"Model S" = "https://www.tesla.com/models";
"Model X" = "https://www.tesla.com/modelx";
"Powerwall" = "https://www.tesla.com/powerwall";
"Twitter" = "https://twitter.com/?lang=en";
"Periscope" = "https://www.periscope.tv/";
"Vine" = "https://vine.co/";

所以我可以设置我的 Product 实体的 url 属性(String 类型)。公司和产品词典:

let defaultProducts = ["Apple" : ["iPhone", "iPad", "Macbook"],
                               "Google" : ["Google", "Firebase", "Magic Leap"],
                               "Facebook" : ["Facebook", "Instagram", "WhatsApp"],
                               "Tesla" : ["Model S", "Model X", "Powerwall"],
                               "Twitter" : ["Twitter", "Periscope", "Vine"]]

这是我函数中的相关代码:

let companyProducts = defaultProducts[name]

for productName in companyProducts! {

    let product = NSManagedObject(entity: productEntity, insertInto:managedContext)
    let names = NSLocalizedString(productName, comment:"")

    product.setValue(productName, forKey: "name")
    product.setValue(productName, forKey: "image")
    product.setValue(names, forKey: "url")

    product.setValue(company, forKey: "company")
}

然后我用它来在点击单元格时显示网页

// WebView
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    let managedContext =
        appDelegate.persistentContainer.viewContext

    let entity =
        NSEntityDescription.entity(forEntityName: "Product",
                                   in: managedContext)!

    let product = NSManagedObject(entity: entity,
                                  insertInto: managedContext)

    if let url = product.value(forKey: "url") as? URL {
        webView.load(URLRequest(url: url))
        webView.allowsBackForwardNavigationGestures = true
        view = webView

    }
    print(product.value(forKey: "url") as? URL)
}

我是否在 localized.strings 中做错了什么,导致了 nil 值?

编辑:setDefaults() 与 url 字典:

func setDefaults() {
    let userDefaults = UserDefaults.standard
    let defaultValues = ["firstRun" : true]
    userDefaults.register(defaults: defaultValues)

    if userDefaults.bool(forKey: "firstRun") {
        let defaultProducts = ["Apple" : ["iPhone", "iPad", "Macbook"],
                               "Google" : ["Google", "Firebase", "Magic Leap"],
                               "Facebook" : ["Facebook", "Instagram", "WhatsApp"],
                               "Tesla" : ["Model S", "Model X", "Powerwall"],
                               "Twitter" : ["Twitter", "Periscope", "Vine"]]

        let urlDictionary = ["iPhone" : "http://www.apple.com/iphone/",
                           "iPad" : "http://www.apple.com/ipad/",
                           "Macbook" : "http://www.apple.com/macbook/",
                           "Google" : "https://www.google.com/",
                           "Firebase" : "https://firebase.google.com/",
                           "Magic Leap" : "https://www.magicleap.com/",
                           "Facebook" : "https://www.facebook.com/",
                           "Instagram" : "https://www.instagram.com/?hl=en",
                           "WhatsApp" : "https://www.whatsapp.com/",
                           "Model S" : "https://www.tesla.com/models",
                           "Model X" : "https://www.tesla.com/modelx",
                           "Powerwall" : "https://www.tesla.com/powerwall",
                           "Twitter" : "https://twitter.com/?lang=en",
                           "Periscope" : "https://www.periscope.tv/",
                           "Vine" : "https://vine.co/"]

        let companyEntity = NSEntityDescription.entity(forEntityName: "Company", in: managedContext)!
        let productEntity = NSEntityDescription.entity(forEntityName: "Product", in: managedContext)!

        // Setting the default company data (name, logo, and stockPrice)
        let url = URL(string: "https://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20Ask%2C%20YearHigh%2C%20YearLow%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22%2C%22GOOG%22%2C%22TWTR%22%2C%22TSLA%22%2C%20%22FB%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys")!
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error!)
            } else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
                let json = JSON(data: data!)
                if let quotes = json["query"]["results"]["quote"].array {
                    for quote in quotes {
                        let symbol = quote["symbol"].stringValue
                        let name = NSLocalizedString(symbol, comment:"")
                        let ask = quote["Ask"].stringValue
                        let company = NSManagedObject(entity: companyEntity,insertInto: managedContext)
                        company.setValue(name, forKey: "name")
                        company.setValue(name, forKey: "logo")
                        company.setValue(ask, forKey: "stockPrice")
                        companies.append(company)

                        let companyProducts = defaultProducts[name]

                        for productName in companyProducts! {

                            let product = NSManagedObject(entity: productEntity, insertInto:managedContext)
                            let names = urlDictionary[productName]

                            product.setValue(productName, forKey: "name")
                            product.setValue(productName, forKey: "image")
                            product.setValue(names, forKey: "url")

                            product.setValue(company, forKey: "company")

                        }
                        print(json)
                    }

                    DispatchQueue.main.async {
                        do {
                            try managedContext.save()
                            vc.tableView.reloadData()
                            userDefaults.set(false, forKey: "firstRun")
                        } catch let error as NSError {
                            print("Could not save. \(error), \(error.userInfo)")
                        }
                    }
                }
            } else {
                print("The data couldn't be loaded")
            }
        }
        task.resume()
    }
}

最佳答案

许多问题变得复杂:

  1. didSelectRowAt 代码正在创建新的 Product 实例,而不是根据点击的行使用正确的 Product。对此的修复是替换:

    let product = NSManagedObject(entity: entity, insertInto: managedContext)
    

    与:

    let product = products[indexPath.row]
    
  2. 代码还假定 Product 实体的 url 属性是 URL 类型;事实上它是 String 类型。解决这个问题的方法是更正转换,然后从 String 创建一个 URL:

    if let urlString = product.value(forKey: "url") as? String {
        let url = URL(string:urlString)
    
  3. 最后,NSLocalizedStrings 在创建默认数据时引起了问题。这是通过用字典替换它们来解决的:

    let urlDictionary = ["iPhone" : "http://www.apple.com/iphone/", 
                         "iPad" : "http://www.apple.com/ipad/", etc
    

    然后:

    let names = urlDictionary[productName]
    

关于ios - 从本地化字符串设置核心数据值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41901745/

相关文章:

ios - NSInvalidArgumentException',原因: 'Unable to parse the format string "userName like %@ password like % @"'

ios - 可以为 iPhone 添加哪个 slider View Controller

iphone - 在整个应用程序中使用此 NSManagedObjectContext 是一种好习惯吗

iphone - AFNetworking with CoreData 线程安全吗?

用于移动网络的 Facebook Like 按钮

javascript - 将 obj-c 类传递给 javascript 不起作用。我究竟做错了什么?

c++ - 如何将 WebKit 嵌入到我的 C/C++/Win32 应用程序中?

ios - 修复静态 tableviewcontroller xcode 8 中 Storyboard 中的所有警告

ios - 1 个屏幕包含 2 个 View Controller 的最佳方法

iphone - CGContextRestoreGState 好像没有恢复之前的状态