无法将对象添加到NSMutableArray

时间:2014-10-04 00:17:25

标签: swift nsmutablearray

我试图加载一个可变阵列并卡住了。

基本上我想要做的是能够将任何类对象添加到全局数组。在这个例子中,我只有名字和地址。

这是一个游乐场片段:

import Foundation
var gDownloaders:NSMutableArray?

class downloader {
    var name:String?
    var address:String?
    init(name:String, address:String) {
        self.name = name
        self.address = address
    }
}

let one = downloader(name: "Ric Lee", address: "901 Edgewood")
let two = downloader(name: "Richard Brauer", address:"1010 Red Oak")
let three = downloader(name: "Meredith Lind", address: "410 Sunset Blvd")

gDownloaders?.addObject(one)
gDownloaders?.addObject(two)
gDownloaders?.addObject(three)

println(gDownloaders)

顺便说一句:Xcode 坚持我有'?' / gDownloaders。

对于gDownloaders,我得到的只是零;即使这三个对象中的每一个都是真实的数据。

我做错了什么?

...我应该使用Array vs NSMutableArray类吗?

2 个答案:

答案 0 :(得分:2)

您永远不会初始化gDownloaders。你声明了变量gDownloaders应该具有的变量类型,但是你不能在该变量中放置任何东西。

尝试:

var gDownloaders:NSMutableArray? = NSMutableArray()

答案 1 :(得分:0)

快速地,在操场上试试这个:

import Foundation

class downloader {
    var name:String?
    var address:String?
    init(name:String, address:String) {
        self.name = name
        self.address = address
    }
}

var gDownloaders = [downloader]()

let one = downloader(name: "Ric Lee", address: "901 Edgewood")
let two = downloader(name: "Richard Brauer", address:"1010 Red Oak")
let three = downloader(name: "Meredith Lind", address: "410 Sunset Blvd")

gDownloaders.append(one)
gDownloaders.append(two)
gDownloaders.append(three)

println(gDownloaders[0].name!)