Search code examples
iosswiftcastingnsnotificationcenteruserinfo

how to send array of objects using NSNotification -> userInfo in Swift


userInfo only sends data of type anyObject , so I need to cast my array of Meals to anyObject without crashing and then recasting it to [Meal], unfortunately it crashes here ...

var anyOrder =  NSMutableArray()
    for meal in ordered { // ordered is array of meals [Meal] ...
        anyOrder.addObject(meal as! AnyObject) //crashes here 
    }

I want to be able to cast it or find any other way to send it using userInfo in NSNotification, thanks in advance


Solution

  • I'd like to know the type of Meal.

    If Meal inherit AnyObject, you can cast that easily.

    class Meal: AnyObject {
        // something
    }
    
    var ordered = [Meal(), Meal()]
    
    var anyOrder =  NSMutableArray()
    for meal in ordered {
        anyOrder.addObject(meal as AnyObject)
    }
    

    If not so, whether or not Meal can cast AnyObject depends on inheritors. Considering from crash, you failed to cast it. So the runtime error happen.