首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从本地化字符串设置核心数据值

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

Stack Overflow用户
提问于 2017-01-27 19:37:45
回答 1查看 103关注 0票数 1

编辑:代码现在正在工作,原来它是陈旧的数据。我保存并清理了这个项目,重新设置了模拟器,现在它开始工作了!谢谢你帮我解决问题!

我仍然习惯于核心数据和本地化字符串,所以我不确定我是否不正确地使用本地化字符串,或者问题是否在其他地方,但是当我点击单元格时,我可以通过我的print语句看到所有值都为零,而且显然没有加载任何网页。

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

代码语言:javascript
运行
复制
"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/";

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

代码语言:javascript
运行
复制
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"]]

下面是我函数中的相关代码:

代码语言:javascript
运行
复制
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")
}

然后,当单元格被点击时,我使用它来显示网页。

代码语言:javascript
运行
复制
// 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字典:

代码语言:javascript
运行
复制
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()
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-30 20:37:19

一些问题更加复杂:

  1. didSelectRowAt代码创建了新的Product实例,而不是根据所点击的行使用正确的Product。这方面的解决办法是取代: 设乘积=NSManagedObject(实体:实体,insertInto: managedContext) 通过以下方式: 设乘积= productsindexPath.row
  2. 代码还假定Product实体的Product属性是URL类型的;实际上,它是String类型的。修复方法是更正强制转换,然后从String创建一个String: 如果让urlString = product.value(forKey:"url") as?字符串{ let url = URL( String :urlString)
  3. 最后,在创建默认数据时,NSLocalizedStrings会导致问题。这是通过用字典代替它们来解决的: 设urlDictionary = ["iPhone“:"http://www.apple.com/iphone/"”,"iPad“:"http://www.apple.com/ipad/"等” 然后: 让名字= urlDictionaryproductName
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41901745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档