Swift addObject
A couple of issues:
You suggested that you were trying to add the city with the following line of code:
citiesArray.addObject(City())
The
City()
construct will instantiate a new, blankCity
object. So that line of code would, best case scenario, add a blankCity
object to your array, which is not what you intended.When you add the
city
to yourcitiesArray
, you should simply:citiesArray.addObject(city)
You say you've defined your
citiesArray
like so:var citiesArray: NSMutableArray!
You also need to instantiate an object for this variable (i.e. create an object to which this variable will now point), e.g.:
citiesArray = NSMutableArray()
You are reporting, though, that at the end of this loop, that
citiesArray
isnil
. Really?!? But if you tried to call theaddObject
method andcitiesArray
wasnil
, you could have received a fatal error: "unexpectedly found nil while unwrapping an Optional value".So, if
citiesArray
wasnil
, thenjsonArray
must have been empty, too. Or for some reason you didn't even get to this loop. I would suggest (a) loggingjsonArray
; and (b) log or put breakpoint inside this loop and confirm you're even getting in here like you think you are.Also, check the timing of this (i.e. make sure your statement logging
citiesArray
is actually taking place after this routine that populates it). I know that sounds crazy, but if you are retrieving the data from some network resource asynchronously, you could have some timing related issues.Since you're writing Swift code, you might consider using Swift arrays. For example, define your array variable as
var citiesArray: [City]!
And instantiate it with:
citiesArray = [City]()
And add objects to it with:
citiesArray.append(city)
I am pretty sure you need to use the append function:
citiesArray.append(city)
or
if you want to append at the start of the array
citiesArray.insert(city, atIndex: 0)
instead of
citiesArray.addObject(City())
here is a little example: Syntax might not be 100% not on comp with xcode right now.
var strA:String = "apple" var strB:String = "pineapple" var strArr = ["kiwi", "mango", "lime"] strArr.append(strA) println(strArr.count) //4 ["kiwi", "mango", "lime", "apple"] citiesArray.insert(strB, atIndex: 0) println(strArr.count) //5 ["pineapple", "kiwi", "mango", "lime", "apple"]