While getting into a nice long argument over memory locations vs pointers vs associated objects, we stumbled across a little bit of a headache: While setters may set the memory address of passed objects equal to each other, does said passed object, in turn have the same associated object?

In theory, it would make sense, as any objects that share the same memory address must have the same associated object because they are the same object, right?

有帮助吗?

解决方案

You can't have two Objective-C objects (or primitives, or structs, or any other data structure for that matter) occupying the same memory address.* If you have what appears to be two objects, which are located at the same spot in memory, then you in fact have one object.

We use pointers to access objects. If you set one pointer to another, using a simple assignment:

NSString * s = [NSString stringWithContentsOfFile:@"README"];
NSString * t = s;

then you have two pointers to one single object. There is no copying of objects. If you change one of the object's ivars via one pointer, then when you look at the object via the other pointer, you see the changed value.


*Full pedantry: sure, you could re-interpret the data at a particular location (see "The Story of Mel") but that's black magic that's beyond the scope of this question.

其他提示

When you say you pass an object what you'r passing is a pointer, not an object. And what is set is the memory address.

When a new pointer with a memory address pointing to the associated object is passed to the setter method, and the object inside is set to the new address, now both pointers (the one passed and the one set) have the same memory address and they share the same associated object.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top