kesa
kesa

Reputation: 3

'AnyObject?' does not have a member named 'count'

I'm trying to loop through an (as I would interpret) array by arrayname.count like:

if var storedToDoItems: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") {  
        toDoItems = []

        for var i = 0; storedToDoItems.count; i++ {
            toDoItems.append(storedToDoItems[i] as NSString)
        }
    }

and receive the error in the title marked by storedToDoItems.count. I'm populating first storedToDoItems like this:

...
    toDoItems.append(tb_toDoItem.text)

    let fixedToDoItems = toDoItems

    // Store items
    NSUserDefaults.standardUserDefaults().setObject(fixedToDoItems, forKey: "toDoItems")

    // Save the stored stuff
    NSUserDefaults.standardUserDefaults().synchronize()
...

Upvotes: 0

Views: 972

Answers (3)

Abhishek Maheshwari
Abhishek Maheshwari

Reputation: 361

I just used this Bold line will work for you hopefully

if var toDoStored: [String] = NSUserDefaults.standardUserDefaults().objectForKey("toDoSaved") as? [String]{

         tblItems = []

        for var i = 0; i < toDoStored.count ; ++i  {
         tblItems.append(toDoStored[i] as NSString)
        }

    }

Upvotes: 0

Antonio
Antonio

Reputation: 72760

If you store an array to the user defaults, you should try to cast it to an array when you extract it.

If toDoItems is defined as an array of strings [String], then you just have to use optional binding combined with optional cast, and just copy the extracted array to toDoItems:

if let storedToDoItems: [String] = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {
    toDoItems = storedToDoItems
}

Being an array a struct, i.e. a value type, it is assigned by copy, so when assign storedToDoItems to toDoItems, a copy of it is created and assigned - so you don't need to manually add each element individually.

Your code instead has 2 errors:

  • you have defined storedToDoItems as an optional AnyObject, and optionals don't have a count property.
  • even if it is not defined as optional, AnyObject doesn't have a count property as well. It's irrelevant that the actual type stored in the variable is an array, the variable is declared as AnyObject and that is how is treated by the compiler.

Upvotes: 1

qwerty_so
qwerty_so

Reputation: 36313

You need to tell what's inside:

toDoItems = [String]()
if let storedToDoItems = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {
    for item in storedToDoItems {
        toDoItems.append(item)
    }
}

and even shorter:

toDoItems = [String]()
if let storedToDoItems = NSUserDefaults.standardUserDefaults().objectForKey("toDoItems") as? [String] {
    toDoItems = storedToDoItems
}

Upvotes: 0

Related Questions