加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift中的类方法和实例方法有什么区别?

发布时间:2020-12-14 04:43:30 所属栏目:百科 来源:网络整理
导读:protocol NoteProtocol { var body: NSString? { get set } var createdAt: NSDate? { get set } var entityId: NSString? { get set } var modifiedAt: NSDate? { get set } var title: NSString? { get set } // class methods class func insertNewNoteIn
protocol NoteProtocol {
    var body: NSString? { get set }
    var createdAt: NSDate? { get set }
    var entityId: NSString? { get set }
    var modifiedAt: NSDate? { get set }
    var title: NSString? { get set }

    // class methods
    class func insertNewNoteInManagedObjectContext(managedObjectContext: NSManagedObjectContext!) -> NoteProtocol
    class func noteFromNoteEntity(noteEntity: NSManagedObject) -> NoteProtocol

    // instance methods
    func update(#title: String,body: String)
    func deleteInManagedObjectContext(managedObjectContext: NSManagedObjectContext!)
}

你好
这是我在GitHub上找到的一段代码.在这个协议中,类方法和实例方法之间的主要区别是什么?它们是如何定义的?
谁能帮我?

解决方法

the documentation的一些文字:

实例方法

Instance methods are functions that belong to instances of a particular class,structure,or enumeration. They support the functionality of those instances,either by providing ways to access and modify instance properties,or by providing functionality related to the instance’s purpose.

即.类的实例必须调用此方法.示例:

var a:classAdoptingNoteProtocol=classAdoptingNoteProtocol()
a.update()

分类方法

Instance methods,as described above,are methods that are called on an instance of a particular type. You can also define methods that are called on the type itself. These kinds of methods are called type methods. You indicate type methods for classes by writing the keyword class before the method’s func keyword,and type methods for structures and enumerations by writing the keyword static before the method’s func keyword.

它们在其他语言中被称为静态方法.要使用它们,这就是我要做的:

var b=classAdoptingNoteProtocol.noteFromNoteEntity(...)

这将返回采用NoteProtocol的类的实例.即.您不必创建类的实例来使用它们.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读