How to write my own setter for an ivar, i.e.: self.ivar = …?

前端 未结 2 926
抹茶落季
抹茶落季 2021-01-06 19:04

This is a follow-up question of: Difference between self.ivar and ivar? :

self.name = @\"hello\";

I would like to know what is done inside

2条回答
  •  伪装坚强ぢ
    2021-01-06 19:56

    The basic answer is that you need to define a method called "setXXX:" where "XXX" is the name of your property, starting with a capital letter, e.g. if your property is called "name", then your setter should be called "setName:". In this method, you should make the assignment of the argument to your actual ivar.

    That said, dreamlax is correct in that there is more to it. When you declare your property, you define a contract regarding how the assignment will work regarding things like thread-safety and memory management. Apple has great documentation on this subject, and I suggest you check it out:

    http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html%23//apple_ref/doc/uid/TP30001163-CH17-SW14

提交回复
热议问题