我一直在努力在 NSArray 中循环解析它,然后将它添加到 NSMutableArray。问题不在于解析我想遍历整个 NSArray。
这是我的代码:
if let dictionarys : NSArray = dictionary.valueForKey("response") as? NSArray {
var categoryNum = 0
var currency = "0"
if let category: NSArray = dictionarys.valueForKey("category") as? NSArray {
if let catId = category.valueForKey("categoryID") as? NSArray {
categoryNum = catId[0] as! Int
}
}
if let currency1: NSArray = dictionarys.valueForKey("currency") as? NSArray {
if let currency2 = currency1[0] as? String {
currency = currency2
}
}
serviceObject = ServicesObject(categoryId: categoryNum,currency: currency)
CategoryItems.addObject(serviceObject)
}
self.tableView.reloadData()
我想做这样的事情:
for (var i = 0;i<dictionarys.count ; i++){
var categoryNum = 0
var currency = "0"
if let category: NSArray = dictionarys.valueForKey("category") as? NSArray {
if let catId = category.valueForKey("categoryID") as? NSArray {
categoryNum = catId[0] as! Int
}
}
if let currency1: NSArray = dictionarys.valueForKey("currency") as? NSArray {
if let currency2 = currency1[0] as? String {
currency = currency2
}
}
serviceObject = ServicesObject(categoryId: categoryNum,currency: currency)
CategoryItems.addObject(serviceObject)
}
我尝试解析的示例:print(dictionarys)
(
{
category = {
category = "<null>";
categoryID = 66;
};
currency = 2;
},{
category = {
category = "<null>";
categoryID = 66;
};
currency = 2;
},{
category = {
category = "<null>";
categoryID = 66;
};
currency = 2;
}
)
最佳答案
我使您的示例更加 Swifty,并添加了一些模拟类以使其在一个简单的 Playground 中运行:
import Foundation
class ServicesObject {
var categoryId: Int
var currency: String
init(categoryId: Int, currency: String) {
self.categoryId = categoryId
self.currency = currency
}
}
class CategoryItems {
static func addObject(item: ServicesObject) {
print("Added categoryID \(item.categoryId), currency \(item.currency)")
}
}
let dictionary: NSArray = [
["response":
["category":
["category":"<null>",
"categoryID":66],
"currency": "2"]],
["response":
["category":
["category":"<null>",
"categoryID":67],
"currency": "3"]],
["response":
["category":
["category":"<null>",
"categoryID":68],
"currency": "4"]]]
if let responses = dictionary.valueForKey("response") as? NSArray {
for response in responses where response is NSDictionary { // loop over all responses
var categoryNums = 0
if let category = response["category"] as? NSDictionary {
categoryNums = category["categoryID"] as? Int ?? 0
}
var currency = response["currency"] as? String ?? "0"
let serviceObject = ServicesObject(categoryId: categoryNums, currency: currency)
CategoryItems.addObject(serviceObject) // add all responses
}
}
里面有一些更奇特的东西,比如 nil coalescing operator (??
)但希望它能作为一个例子。
关于ios - 在 NSArray 中循环并将对象添加到 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35064041/