I've been working my way through the book, and everything has been making sense, but I've just reached Chapter 17 - memory management - and I'm confused. I had some questions about memory management as I worked through the text, and I thought Ch 17 would clarify all, but so far it hasn't.
Here are my questions, hopefully someone can help...
1. In all of the sample programs, we've been creating an NSAutoreleasePool as our first line of code within main(). How do the objects know to use that pool? Is it because it is the only pool that exists? What if we created two pools? Which one would they use?
2. Sometimes the books uses class methods that allocate the memory for you, and other times it doesn't. How do we choose which approach to take? What are the decision criteria? For example, the NSString class method "stringWithString:" allocates the memory for you (?). I think I understand why in program 15.8 we modify the code on page 349 to allocate the memory ourselves, using the "alloc" class method - because we are initializing an instance variable, and we want to 'own' that variable. Is that right? What about in other cases?
3. In program 15.4, when I look at it now, after reading Ch 17, I seem to think that we are leaking memory all over the place - or maybe not. I have a bunch of questions about this example...
NSString *str1 = @"This is string A"
I think I'm OK with that.
This is creating a pointer to a string, but doing no allocation or initializing, correct?
res = [str1 substringToIndex: 3];
I believe that this is creating a new string, and making res point to it. If so, does this mean that the substringToIndex: method is allocating and initializing for us? (because we certainly didn't allocate it ourselves)
res = [str1 substringFromIndex: 5];
I believe that this is creating a new string, and re-pointing res to it.
If that is correct, what happens to the string where res was previously pointing? (from the call to substringToIndex:) Is this a memory leak? Or, is NSString class responsible for deallocating its memory?
Answers greatly appreciated.