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

前端 未结 3 1408
生来不讨喜
生来不讨喜 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: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.

提交回复
热议问题