如何将数据附加到 ios swift 中的 NSMutableArray

How to append data in to NSMutableArray in ios swift

我目前正在开发一个食品订购应用程序,当我将项目添加到任何数组时,我需要通过 CartDataModal 将这些项目传递给 cartVC,其中 cartArrayDictNSMutableArray 类型。但是当我插入 SelectedDict 时,应用程序崩溃了,谁能帮我解决这个问题?

这是我的代码:

var restMenu = [[String:Any]]()

func addTapped(cell: RestaurantItemViewCell)
{
    //get the indexPath for add button click
    let indexPath = self.restTableView.indexPath(for: cell)
     print("the indexPath is", indexPath?.row)

    print("all obj is",restMenu)

    var selectedDict = restMenu[(indexPath?.row)!]
    print("selected dict is",selectedDict)

     selectedDict["ItemQuant"] = cell.itemQuantityLabel.text

    print("selected dict is",selectedDict)


    // Append In Cart Modal
    CartDataModal.shared_Inst.cartArrayDict.insert(selectedDict, at: (indexPath?.row)!)


    print("rest menu is",restMenu)

    restMenu.remove(at: (indexPath?.row)!)
    print("rest menu is",restMenu)

    restMenu.insert(selectedDict, at: (indexPath?.row)!)

    print("restmenu is",restMenu)
}

我的购物车数据模式:

class CartDataModal: NSObject {
    static let shared_Inst = CartDataModal()
    var cartArrayDict: [String:Any]!
}

来自我的 ViewController 我正在从我的 Restaurant.plist

获取数据
func moveToDetailController(img:UIImage,name:String)
{
    print("the rest name is", name)

    let pathUrl =  Bundle.main.path(forResource: "ResturantFile", ofType: ".plist")
    print("path url is",pathUrl as Any)

    let finalArray = NSMutableArray(contentsOfFile: pathUrl!)
    print("final Array is",finalArray)

    let restaurantNames = finalArray?.firstObject as? NSDictionary
    print("resturant name is",restaurantNames as Any)


    if let menuDataArray:[[String:Any]] = restaurantNames?.value(forKey: name) as? [[String:Any]]
    {

        print("menu data is",menuDataArray)

    let restVC = self.storyboard?.instantiateViewController(withIdentifier: "RestaurantViewController") as! RestaurantViewController

    restVC.tempImg = img
    restVC.tempTitle = name

    restVC.restMenu = menuDataArray

    self.navigationController?.pushViewController(restVC, animated: true)
    }
}

您需要修改结构:

class CartDataModal: NSObject {

static let shared_Inst = CartDataModal()

var cartArrayDict = [[String: Any]]()

}

插入前需要初始化字典数组。所以你可以在struct中初始化,也可以根据你的用途在使用前初始化。