简体   繁体   中英

Loop in NSArray and add Object to NSMutableArray

I have been trying so hard to loop in NSArray parse it and then add it to NSMutableArray. the issue is not with parsing i wanted to loop over the whole NSArray.

Here is my code:

 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()

i want to do something like this :

            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)

}

a sample of what I'm trying to parse i did : print(dictionarys)

(
        {
        category =         {
            category = "<null>";
            categoryID = 66;
        };
        currency = 2;

    },{
        category =         {
            category = "<null>";
            categoryID = 66;
        };
        currency = 2;

    },{
        category =         {
            category = "<null>";
            categoryID = 66;
        };
        currency = 2;

    }
)

I've taken your JSON sample and made this very simple example for you to get the idea of a proper Swift loop, this is probably what you need to adapt for your actual code base and data.

Given that "dictionarys" is an NSArray of NSDictionaries:

for dict in dictionarys {
    if let curr = dict["currency"] as? Int {
        print("Currency: \(curr)")
    }
    if let category = dict["category"] as? NSDictionary {
        if let ID = category["categoryID"] as? Int {
            print("ID: \(ID)")
        }
    }
}

I made your example a bit more Swifty and added some mocked classes to get it all to work in a simple 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
  }
}

There's some fancier stuff in there such as the nil coalescing operator ( ?? ) but hopefully it will work as an example.

您可以尝试使用另一个数组初始化该数组。

var nsmutablearrayVariableName = NSMutableArray.init(array: nsarrayVariableName)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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