'AnyObject'没有名为'note'的成员

时间:2015-04-22 10:21:11

标签: ios swift

寻求更多帮助。我有一个自我声明的对象,我有两个属性'date and note'。在下面的代码日期可以在instanciated对象中引用,但注意不能。有什么想法吗?

这是错误所在的详细视图控制器。 10号线和20号线。

import UIKit

class DetailViewController: UIViewController {


@IBOutlet weak var tView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
tView.text = allNotes[currentNoteIndex].note
tView.becomeFirstResponder()
}

override func viewDidDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    if tView.text == "" {
        allNotes.removeObjectAtIndex(currentNoteIndex)
    }
    else {
        allNotes[currentNoteIndex].note = tView.text
    }
    Note.saveNotes()
    noteTable?.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

这是note.swift文件,您可以在其中看到变量。

import UIKit

var allNotes:NSMutableArray = []
var currentNoteIndex:Int = -1
var noteTable:UITableView?

let KAllNotes:String = "notes"


class Note: NSObject {
var date:String
var note:String

override init() {
    date = NSDate().description
    note = ""
}

func dictionary() -> NSDictionary {
    return ["note":note, "date":date]
}

class func saveNotes() {
    var aDictionaries:NSMutableArray = []
    for var i:Int = 0; i < allNotes.count; i++ {
        aDictionaries.addObject(allNotes[i].dictionary())
    }
//        NSUserDefaults.standardUserDefaults().setObject(aDictionaries, forKey: KAllNotes)
    aDictionaries.writeToFile(filePath(), atomically: true)
}

class func loadnotes() {
    var defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
//        var savedData:[NSDictionary]? = defaults.objectForKey(KAllNotes) as? [NSDictionary]
    var savedData:NSArray? = NSArray(contentsOfFile: filePath())
    if let data:NSArray = savedData {
        for var i:Int = 0; i < data.count; i++ {
            var n:Note = Note()
            n.setValuesForKeysWithDictionary(data[i] as! [NSDictionary : AnyObject])
            allNotes.addObject(n)
        }
    }
}

class func filePath() -> String {
    var d:[String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
    if let directories:[String] = d {
        var docsDirectory:String = directories[0]
        var path:String = docsDirectory.stringByAppendingPathComponent("\(KAllNotes).notes")
        return path;
    }
    return ""
}
}

2 个答案:

答案 0 :(得分:3)

由于您将allNotes声明为NSMutableArray,编译器无法知道其元素的类型,因此每个对象都将被视为AnyObject

您需要向编译器提供allNotes包含Note类型对象的信息。

您可以在从数组中检索对象时强制转换对象

(allNotes[currentNoteIndex] as! Note).note

或(最好)使用类型化的快速数组

var allNotes: [Note] = []

答案 1 :(得分:1)

这是因为allNotes不是Note的类型。因此,出于安全考虑,您必须将var allNotes:NSMutableArray = []声明为var allNotes = [Note]()