开发者

Cannot understand getter/setter with object

It is easy to understand the concept of setter/getter for a simple data, an NSInteger for example.

If we say: NSInteger a;

The setter for "a" changes the value of a, and the getter only gets (returns) its value. It is then easy to understand atomic/nonantomic concept since atomic will guarantee that reading "a" when a is being chnaged will always return a whole value (getter and setter are synchronized).

But what I do not clearly understand is setter and getter for properties which are pointers to objects (NSData*, NSString* for examp开发者_运维百科le). Let's say for example a NSMutableData:

If we say: NSMutableData *m_my_mutable;

Imagine I have a setter setMyMutable and getMyMutable for this property which belongs to my object MyObject. If I do this, then I will call the getter (since I get the object before appending data):

[[MyObject getMyMutable] appendData....]

but appendingData will also modify it, thus sould not it be seen as a setter action instead ? Or does setter only refer to the fact of initiliazing a value (which can be retained for example).

There is something I must be missing in the concept.

Thanks Apple92


A setter sets the value of a property. When you set an integer property, a new integer value is stored. When you set an object property, a new object is stored. appendData: does not change the property — it changes the data object itself. An atomic property will only ensure that the property holds some complete value or another — it doesn't affect what you do with the object inside the property.

Incidentally, having mutable state (such as an NSMutableData object) that's accessible outside the owning object is almost always a bad idea. Once you do that, it becomes way too easy to have multiple objects all trying to make their own changes and stomping over each other.


Setting does indeed only refer to initialization. This is why atomicity is not enough to ensure that mutable data structures are thread-safe. Instead, the guarantee you get is that the object will only be replaced or read in one fell swoop, so you don't end up with partial assignments.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜