简体   繁体   English

如何快速使用全局解析的值

[英]how to globally used parsed values in swift

func jsonParsing1(){
           do{
            let path : NSString =  NSBundle.mainBundle().pathForResource("fileName", ofType: "json")!
            let data : NSData = try! NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMappedIfSafe)
            let jsonData = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
            let jsonArray = jsonData
           ** let templeArray = (jsonArray.valueForKey("temple-name") as? NSArray)!**

           }catch {
           print(error)


        }
    }
}

my json files is [ { “temple-name”: "aaa", “image”: "image.png”, “description”: “aaa“ }, { “temple-name”: "bbb", “image”: "image1.png”, “description”: “bbb“ } ] I am using json file in a separate class and trying to access the parsed array all through the project. 我的json文件是[{“ temple-name”:“ aaa”,“ image”:“ image.png”,“ description”:“ aaa”},{“ temple-name”:“ bbb”,“ image”: “ image1.png”,“ description”:“ bbb”}]我在一个单独的类中使用json文件,并尝试在整个项目中访问已解析的数组。 Used global array but it returns nil when calling from another class. 使用了全局数组,但从另一个类调用时返回nil。 Thanks in advance. 提前致谢。

I need to use the templeArray globally. 我需要全局使用TempleArray。

You can create a singleton class with templeArray property, store the value in this array and access it through shared instance of the singleton class. 您可以创建带有TempleArray属性的单例类,将值存储在此数组中,并通过单例类的共享实例进行访问。 Or, 要么,

You can declare templeArray property in appDelegate and global access to it. 您可以在appDelegate中声明TempleArray属性,并对其进行全局访问。

You can static variables to access data across your project. 您可以使用static变量来访问整个项目中的数据。

class GlobalVariables {
    static var templeArray : NSMutableArray?
}

You can use templeArray throughout your application via 您可以通过templeArray在整个应用程序中使用templeArray

GlobalVariables.templeArray?.objectAtIndex(index)

Please try this kind of approach: 请尝试这种方法:

class MyClass {

static var templeArray : NSArray?


     func jsonParsing1(){
        let path : NSString =  NSBundle.mainBundle().pathForResource("fileName", ofType: "json")!
        let data : NSData = try! NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMappedIfSafe)
        let jsonData = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
        let jsonArray = jsonData
        MyClass.templeArray = (jsonArray.valueForKey("temple-name") as? NSArray)!

        /*
         * You can now access to templeArray in this way:
         * let myArray : NSArray? = MyClass.templeArray
         */
     }
}

In addition, the do/catch block is useless in Swift2. 另外,do / catch块在Swift2中是无用的。

EDIT: You are doing it wrong. 编辑:您做错了。

let templeArray = (jsonArray.valueForKey("temple-name") as? NSArray)!

will always be nil because the field temple name isn't an array, it is a string. 由于字段模板名称不是数组,而是字符串,因此始终为nil。 You have to do: 你必须做:

MyClass.templeArray = jsonArray

Then you can access the first temple this way: 然后您可以通过以下方式进入第一个寺庙:

let temple = MyClass.templeArray[0]
let templeName : String = temple.objectForKey("temple-name") as? String

This code should work: 此代码应工作:

var templeArray: NSMutableArray = []

class Parser {

    func jsonParsing1() {
        do {
            let path : NSString =  NSBundle.mainBundle().pathForResource("fileName", ofType: "json")!
            let data : NSData = try NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMappedIfSafe)
            let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
            let jsonArray = jsonData
            if let rawTempleArray = jsonArray.valueForKey("temple-name") as? NSMutableArray {
                templeArray = rawTempleArray
            } else {
                print("temple-name is not array")
            }
        } catch {
            print(error)
        }
    }
}

I would do like this: 我会这样:

struct Temple { //or class
    // your fields here
    init? (templeDictionary: NSDictionary) {
        // your parser here
    }
}


class TheParser {
    static var theTempleArray: [Temple] = []

    func jsonParsing1() {
        do {
            let path : NSString =  NSBundle.mainBundle().pathForResource("fileName", ofType: "json")!
            let data : NSData = try NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMappedIfSafe)
            let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
            let jsonArray = jsonData
            if let rawTempleArray = jsonArray.valueForKey("temple-name") as? NSArray {
                for temple in rawTempleArray {
                    if let theTemple = temple as? NSDictionary { // or NSArray or String depending of your json structure
                        if let templeItem = Temple(templeDictionary: theTemple) {
                            TheParser.theTempleArray.append(templeItem)
                        }
                    }
                }
            } else {
                print("temple-name is not array")
            }

        } catch {
            print(error)

        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM