微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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的类的实例.即.您不必创建类的实例来使用它们.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐