loaded array from plist. call using AppDelegate() returns empty array.

In app delegate I'm trying to load an array with strings from a plist. I print the plist it prints fine...

func loadTypesArray() {
        guard let path = Bundle.main.path(forResource: "Types", ofType: "plist") else {return}
        let url = URL(fileURLWithPath: path)
        let data = try! Data(contentsOf: url)
        
        guard let plist = try! PropertyListSerialization.propertyList(from: data, options: .mutableContainers, format: nil) as? [String] else {return}
        
        print(plist)
        typesArray = plist
//        print(typesArray)
    }

But when I try and access it from a different part of the app using let typesArray = AppDelegate().typesArray

the array I get is an empty array! any help?

Answered by Claude31 in 789653022

Could you show your complete AppDelegate code ?

There is probably a problem here:

let typesArray = AppDelegate().typesArray

you create a new instance of AppDelegate (as AppDelegate() is a call to init to create a new instance), which itself has an empty typesArray as long as loadTypesArray has not been called. Hence let typesArray = returns empty array.

If typesArray is declared as static in AppDelegate, then you can call

  • in loadTypesArray:
        AppDelegate.typesArray = plist  // Need to refer to class because of static
  • Elsewhere:
let typesArray = AppDelegate.typesArray  // No ()
Accepted Answer

Could you show your complete AppDelegate code ?

There is probably a problem here:

let typesArray = AppDelegate().typesArray

you create a new instance of AppDelegate (as AppDelegate() is a call to init to create a new instance), which itself has an empty typesArray as long as loadTypesArray has not been called. Hence let typesArray = returns empty array.

If typesArray is declared as static in AppDelegate, then you can call

  • in loadTypesArray:
        AppDelegate.typesArray = plist  // Need to refer to class because of static
  • Elsewhere:
let typesArray = AppDelegate.typesArray  // No ()

NSPropertyListSerialization should be helpful in converting your property list for use in code. Also you should try and use AppDelegate.shared and get the singleton instance. When you instantiate a new instance with AppDelegate() it is only available in that scope. The AppDelegate.shared instance is static and available to all classes in the same target or process.

loaded array from plist. call using AppDelegate() returns empty array.
 
 
Q