NSString property copy or readonly?

后端 未结 2 521
别跟我提以往
别跟我提以往 2021-02-03 14:25

I see many discussions saying that I should use copy for NSString property because it will prevent others from changing it behind my back. But then why don\'t w

2条回答
  •  执念已碎
    2021-02-03 15:11

    If you don't want others to modify your property, then you absolutely should mark it readonly. What people mean when they say using copy means the string can't be changed behind your back is, if someone assigns a string to your property, and the string is mutable, and then they mutate the string, when you later access your property you'll get back the changed string. But if you use copy then you'll get back a snapshot of how the string looked at the time it was assigned to the property (which is what people expect to happen).

提交回复
热议问题