主要有几点
-
NSJSONSerialization.JSONObjectWithData
-
as
-
do catch
-
命名空间
private func getJsonData() { let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil) if let jsonPath = path{ let jsonData = NSData(contentsOfFile: jsonPath) //有可能发生异常的代码 do{ let jsonArray = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers) //Swift中遍历数组必须明确数组中的类型 for dict in jsonArray as! [[String:String]] { createChildController(dict["vcName"]!, title: dict["title"]!, image: dict["imageName"]!) } }catch {//发生异常的代码 print(error) //从服务器获取错误 从本地加载 createChildControllersFromLocal() } } }
NSJSONSerialization.JSONObjectWithData这个方法

它会根据json创建一个对象或者出错为nil 第二个参数options
Constants
-
NSJSONReadingMutableContainers Specifies that arrays and dictionaries are created as mutable objects.Available in iOS 5.0 and later.
创建出来的数组和字典是可变的 -
NSJSONReadingMutableLeaves Specifies that leaf strings in the JSON object graph are created as instances of NSMutableString.Available in iOS 5.0 and later.
json中的字符串转换出来是可变字符串 -
NSJSONReadingAllowFragments Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.Available in iOS 5.0 and later.
允许json顶层的对象不是数组或字典
我的英文一般般,如果理解不准确欢迎指正。for dict in jsonArray as! [[String:String]]
类型转换
- 当你不确定向下转型可以成功时,用类型转换的条件形式(as?),它返回的是可选类型。
- 只有你可以确定向下转型一定会成功时,才使用强制形式(as!)
[[String:String]] 把jsonArray转为一个数组,并指明其中存放的是一个字典,键和值都是String类型
do-catch
可以使用一个do-catch语句运行一段闭包代码来处理错误。如果在do子句中的代码抛出了一个错误,这个错误会catch
子句做匹配,从而决定哪条子句能处理它。
下面是do-catch语句的一般形式:
do {
try expression
statements
} catch pattern 1 {
statements
} catch pattern 2 where condition {
statements
}
在catch后面写一个匹配模式来表明这个子句能处理什么样的错误。如果一条catch子句没有指定匹配模式,那么这条子句可以匹配任何错误,并且把错误绑定到一个名字为error的局部常量。
命名空间的概念
//获取命名空间
let namespace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
//将字符串转化为类
let cls:AnyClass? = NSClassFromString(namespace + "." + controllerName)
let vccls = cls as! UIViewController.Type
let vc = vccls.init()
关于命名空间,注意几点
- swift中类名的组成 类名.命名空间
- 一般来首命名空间默认是项目名称
- 通过buildsettings搜索product name可以修改命名空间
具体参见这里
网友评论