Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

JonnyThunder

macrumors member
Original poster
Aug 16, 2008
67
0
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?
 

robbieduncan

Moderator emeritus
Jul 24, 2002
25,611
893
Harrogate
- 1. Why doesn't the last created NSString object exist after the end of the For loop?
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

- 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?

See above regarding scope, but I don't really understand this question at all.
 

JonnyThunder

macrumors member
Original poster
Aug 16, 2008
67
0
Right, OK. I'll read up more on C variables and scopes.

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

thanks,
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.