简体   繁体   中英

Swift 3 Instance member type

I have a func saveNotes() which is a sub-class of NSObject

Note.swift file

func saveNotes() {
        var aDictionaries:[NSDictionary] = []
        for i:Int in 0 ..< allNotes.count {
            aDictionaries.append(allNotes[i].dictionary())
        }
        UserDefaults.standard.set(aDictionaries, forKey: kAllNotes)
    }

When I try to run my project I get an error "Instance member 'saveNotes' cannot be used on type 'Note'; did you mean to use a value of this type instead.

code from MasterViewControler.swift

import UIKit 
import Foundation


class MasterViewController: UITableViewController {

    var objects = NSMutableArray()

    override func viewDidLoad() {
        Note.loadNotes()
        print("allNotes: \(allNotes)")
        var n:Note = Note()
        Note.saveNotes()

Not sure what I'm doing wrong here. Thanks for any help.

The error of:

Instance member 'saveNotes' cannot be used on type 'Note'; did you mean to use a value of this type instead.

is shown by the compiler because you are trying to call a non-instance method directly from the class.

Thus, you would have 2 approaches:

First : Use the declared n instance to call the saveNotes() function:

Note.loadNotes()
print("allNotes: \(allNotes)")
let n:Note = Note()
n.saveNotes()

Second : if you are aiming to call saveNotes() directly from Note class, then it should be declared as static method:

static func saveNotes() { ... }

For more information, you could check Swift Documentation - Method ("Type Methods" section).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM