Code Example: Why can I still access this NSString object after I've released it?

前端 未结 3 1407
生来不讨喜
生来不讨喜 2021-01-20 10:34

I was just writing some exploratory code to solidify my understanding of Objective-C and I came across this example that I don\'t quite get. I define this method and run th

相关标签:
3条回答
  • 2021-01-20 11:27

    The retainCount always printing one is probably caused by optimization - when release notices that its going to be deallocated, there's no reason to update the retainCount to zero (as at this point nobody should have a reference to the object) and instead of updating the retainCount just deallocates it.

    0 讨论(0)
  • 2021-01-20 11:39

    There are a couple of things going on here. First, deallocing an object doesn't necessarily clear any of the memory the object formerly occupied. It just marks it as free. Unless you do something else that causes that memory to be re-used, the old data will just hang around.

    In the specific case of NSString, it's a class cluster, which means that the actual class you get back from alloc/init is some concrete subclass of NSString, not an NSString instance. For "constant" strings, this is an extremely light-weight structure that just maintains a pointer to the C-string constant. No matter how many copies of that striing you make, or how many times you release it, you won't affect the validity of the pointer to the constant C string.

    Try examining [stringPointer class] in this case, as well as in the case of a mutable string, or a formatted string that actually uses a format character and arguments. Probably all three will turn out to have different classes.

    0 讨论(0)
  • 2021-01-20 11:41

    You're getting a double free error because you are releasing twice and causing two dealloc messages. =P

    Keep in mind that just because you release doesn't doesn't mean the data at its memory address is immediately destroyed. It's just being marked as unused so the kernel knows that, at some point in the future, it is free to be used for another piece of data. Until that point (which is totally nondeterministic in your app space), the data will remain there.

    So again: releasing (and dealloc'ing) doesn't necessitate immediate data destruction on the byte level. It's just a marker for the kernel.

    0 讨论(0)
提交回复
热议问题