Variable lifetime and loops

Discussion in 'Mac Programming' started by JonnyThunder, Sep 28, 2008.

  1. macrumors member

    Joined:
    Aug 16, 2008
    #1
    Hi, I took a break and started reading Kochans book again. About a quarter through it - I wrote a little 'mess around' script to add a bunch of strings to a mutable array. Here is the code...

    Code:
    #import <Foundation/Foundation.h>
    
    int main (int argc, const char * argv[]) {
    	
    	// Create a mutable array
    	NSMutableArray *myArray = [[NSMutableArray alloc] init];
    	
    	// A test loop of 10 items
    	for (int i=0; i<10; i++)
    	{
    
    		// Create an NSString object and init with a string
    		NSString *myString = [[NSString alloc] initWithFormat:@"Number is %d", i];
    		
    		// Add the string object to my array
    		[myArray addObject:myString];
    		
    	}
    	
    	// *** The last occurence of myString doesn't exist here. Why not??
    	
        return 0;
    }

    So my understanding is that I'm doing this....

    - 1. Creating a mutable array
    - 2. Looping 0 through to 9
    - 3. (each iteration) Creating a NSString object and adding it to my array


    But I have two basic questions.

    - 1. Why doesn't the last created NSString object exist after the end of the For loop?

    - 2. If the array holds 'pointers' to the NSString objects, how do I still reference those objects directly - considering I'm using the same object name on each iteration and it doesn't exist after the end of the loop?
     
  2. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    Basic C scoping rules. You declared the variable within the loop so that variable is only in scope within the loop. The object still exists in memory: the variable name does not

    See above regarding scope, but I don't really understand this question at all.
     
  3. thread starter macrumors member

    Joined:
    Aug 16, 2008
    #3
    Right, OK. I'll read up more on C variables and scopes.

    Never mind the second question - it makes sense to me now.

    thanks,
     

Share This Page