Immutable Object in Objective-C: Big init method?

后端 未结 2 1236
予麋鹿
予麋鹿 2021-02-10 20:07

I want to have an Object with immutable fields in Objective-C.

In C#, I would use Properties with private setters and a big constructor.

What would I use in Obj

2条回答
  •  再見小時候
    2021-02-10 21:03

    You can make something immutable with the @property keyword; simply make use readonly instead of copy or retain (copy and retain describe the desired behavior on assignment, and so they would not make sense for a property that is readonly). Note that this will result in a getter function being generated when you use @synthesize, but not a setter function. If your data is truly immutable, then it would not make sense to have a setter function, although you could easily create one in the same way that you would create any other method in Objective-C. As for retain vs. copy -- it depends on whether you want to share the object with the caller or whether you want to have a completely independent copy of it. Using retain is more efficient, but it also is a little bit subtle and scary in that your object might possibly be modified from somewhere else through this shared object. It really depends on the guarantees that your class makes and whether such an external modification is ok.

提交回复
热议问题