iOS Swift:向下转换AnyObject

时间:2014-08-18 04:58:05

标签: ios swift downcast

我知道有很多关于从Cocoa到Swift问题的低调问题,并且存在一些问题,但是我已经尝试了很多这里发现的方法而且我无法让它们发挥作用,希望有人能伸出援助之手。 / p>

我是编程新手。我在swift中为iOS制作数据库程序。

我有一个人类:

class Person : NSObject {
    var firstName : String
    var lastName : String

    init (firstName : String, lastName : String) {
        self.firstName = firstName
        self.lastName = lastName
    }

    func encodeWithCoder(aCoder: NSCoder!) {
        aCoder.encodeObject(firstName, forKey:"firstName")
        aCoder.encodeObject(lastName, forKey:"lastName")
}

    init (coder aDecoder: NSCoder!) {
        self.firstName = aDecoder.decodeObjectForKey("firstName") as String
        self.lastName = aDecoder.decodeObjectForKey("lasName") as String
    }

}

我在视图控制器的顶部声明了一个类的数组:

    var peopleArray = [Person]()

然后我通过声明一些示例用户并将其附加到数组来填充数组:

    var nateB = Person(firstName: "Nate", lastName: "Birkholz")
    var nateC = Person(firstName: "Nate", lastName: "Carson")
    var nateD = Person(firstName: "Nate", lastName: "Donnelly")
    self.peopleArray.append(nateB)
    self.peopleArray.append(nateC)
    self.peopleArray.append(nateD)

然后我尝试将数据保存到plist文件中:

let fileManager = (NSFileManager.defaultManager())
        let directorys : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask, true) as? [String]

        println("value of directorys is \(directorys)")

        if (directorys != nil){
            let directories:[String] = directorys!;
            let pathToFile = directories[0]; //documents directory

            let plistfile = "PeopleArray.plist"
            let plistpath = pathToFile.stringByAppendingPathComponent(plistfile);

            if !fileManager.fileExistsAtPath(plistpath){  //writing Plist file

                self.createInitialPeople()

                println("Declaring cocoaArray")
                var cocoaArray : NSArray = [NSKeyedArchiver.archivedDataWithRootObject(peopleArray)]
                println("writing to path")
                cocoaArray.writeToFile(plistpath, atomically: true)
                let tellMe = cocoaArray.writeToFile(plistpath, atomically: true)
                println("Return of write is \(tellMe)")
            } 

创建具有不可知数据的Plist文件。

我关闭应用程序并再次启动它,然后尝试加载文件:

         else {            
            println("\n\nPlist file found at \(plistpath)")

            let cocoaArray = NSMutableArray.arrayWithContentsOfFile(plistpath)
            peopleArray = cocoaArray as Array
        }
    }

我失败了,因为我无法贬低“AnyObject与'Person'不相同。我尝试使用StackOverflow上列出的几种方式对它进行向下转换,但是不能成功。这真是令人沮丧。

使用最终代码进行更新:

func createPeoplePlist() {

    let fileManager = (NSFileManager.defaultManager())
    let directorys : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask, true) as? [String]

    println("value of directorys is \(directorys)")

    if (directorys != nil){
        let directories:[String] = directorys!;
        let pathToFile = directories[0]; //documents directory

        let plistfile = "PeopleArray.plist"
        plistpath = pathToFile.stringByAppendingPathComponent(plistfile);

        if !fileManager.fileExistsAtPath(plistpath){  //writing Plist file

            self.createInitialPeople()

            println("Saving to Plist")

            [NSKeyedArchiver.archiveRootObject(peopleArray, toFile: plistpath)]

            println("writing to path \(plistpath)")


        } else {            //Reading Plist file
            println("\n\nPlist file found at \(plistpath)")

            peopleArray = NSKeyedUnarchiver.unarchiveObjectWithFile(plistpath) as [Person]



        }
    }


}

1 个答案:

答案 0 :(得分:1)

当您重新读取时,您的数组仍然包含NSData(您在首次存档时创建的数据)。但是,我会质疑你为什么在写入磁盘之前将数据放在另一个数组中。 peopleArray本身可以是根对象;不需要额外的数组包装它。然后,您只需使用archiveRootObject(_:toFile:)unarchiveObjectWithFile(_:)

我还建议您阅读Archives and Serializations Programming GuideProperty List Programming Guide以及NSKeyedArchiver文档,以获取更多信息。