Memory leak with NSString - objective-c

I read almost every Question here on SO about memory management that involves NSStrings, but I can't really solve this problem.
#interface:
#property (nonatomic, retain) NSString *criticalTranscription;
#implementation:
viewDidLoad:
criticalTranscription = [[NSString alloc] init];
NSArray *paragraphs = [doc valueForKeyPath:#"critical.text"];
for(int i = 0; i < [paragraphs count]; i++)
{
criticalTranscription = [criticalTranscription stringByAppendingString:[[paragraphs objectAtIndex:i] valueForKey:#"p"]];
criticalTranscription = [criticalTranscription stringByAppendingString:#"\n\n"];
}
[transcription setText:criticalTranscription];
#XIB
A UISegmentedControl with an IBAction linked to:
- (IBAction) changeText:(id)sender
{
if(transcriptionSelector.selectedSegmentIndex == 1)
[transcription setText:diplomaticTranscription];
else
[transcription setText:criticalTranscription];
}
When I change the value of the UISegmentControl (first thing right after loading, nothing else runs), I run into this error (NSZombieEnabled=YES):
2011-07-07 01:10:43.639 Transcribe[404:707] *** -[CFString length]: message sent to deallocated instance 0x1189300
I can't see anything relevant in the backtrace. Without NSZombieEnabled criticalTranscription just points to random arrays or something else. There is no further usage of the variable or any releases.
I ran analyze without any suspicious leaks.
What's the problem?

The problem is that you are overwriting a reference to a string that you own with one that you don't own.
// you own the empty string returned here
criticalTranscription = [[NSString alloc] init];
NSArray *paragraphs = [doc valueForKeyPath:#"critical.text"];
for(int i = 0; i < [paragraphs count]; i++)
{
// immediately overwrite allocated instance (that you own)
criticalTranscription = [criticalTranscription stringByAppendingString:[[paragraphs objectAtIndex:i] valueForKey:#"p"]];
criticalTranscription = [criticalTranscription stringByAppendingString:#"\n\n"];
}
However, don't use this approach, because it pollutes the autorelease pool with unnecessary strings. Instead, use a mutable string and append strings to the single mutable string instance.
Also, in order to utilise the property's built-in memory management, you need to use self.criticalTranscription and not just criticalTranscription. Without the self., you are using the instance variable directly.

In your for loop
criticalTranscription = [criticalTranscription stringByAppendingString:[[paragraphs objectAtIndex:i] valueForKey:#"p"]];
criticalTranscription = [criticalTranscription stringByAppendingString:#"\n\n"];
you are setting criticalTranscription to an autoreleased string object but not retaining it, thus the flaming death.
You could retain it or use a property with #property(nonatomic, copy)NSString *criticalTranscription; and use the property rather than the ivar.

Two problems:
You’re leaking the first instance of the string
Every subsequent value you assign to it is getting autoreleased
To fix it, the easiest way is to change criticalTranscription to an NSMutableString. Then you can do:
criticalTranscription = [[NSMutableString alloc] init];
NSArray *paragraphs = [doc valueForKeyPath:#"critical.text"];
for(int i = 0; i < [paragraphs count]; i++)
{
[criticalTranscription appendString:[[paragraphs objectAtIndex:i] valueForKey:#"p"]];
[criticalTranscription appendString:#"\n\n"];
}
[transcription setText:criticalTranscription];
…alternatively,
[criticalTranscription appendFormat:#"%#\n\n", [[paragraphs objectAtIndex:i] valueForKey:#"p"]];
Also note that you need to call release on criticalTranscription once you’re done with it, either at the end of your -viewDidLoad or in its corresponding -viewDidUnload.

Related

NSObject not retaining

Process -
NSObject Class used to generate a card with certain properties. This is added to a MutableArray and used accordingly. However, after the function to determine the hand outcome in another class, the MutableArray loses all it's values.
Now I know a MutableArray simply points to the objects as opposed to holding them, so for it to lose all it's values I'm assuming the objects are being swept up by ARC.
-(void)rankHand {
NSString *echo = [Hand returnHandRank:_hand withString:false]; // 7 values in _hand
// 0 values in _hand.
NSLog(#"%#", echo);
}
After breakpointing to see the issue, the issue arises after returnHandRank: withString:
#interface Cards : NSObject
#property (nonatomic, strong) NSString *face;
#property (nonatomic, strong) NSString *suit;
#property (nonatomic, strong) NSString *symbol;
#property (nonatomic) int prime;
#property (nonatomic) int rankByInt;
+(NSMutableArray*)createDeck:(id)sender {
[sender removeAllObjects];
NSArray *faces = [[NSArray alloc] initWithObjects:#"A",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9",#"10",#"J",#"Q",#"K", nil];
NSArray *suits = [[NSArray alloc] initWithObjects:#"h",#"d",#"c",#"s", nil];
NSArray *primes = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:41],[NSNumber numberWithInt:2],[NSNumber numberWithInt:3],[NSNumber numberWithInt:5],[NSNumber numberWithInt:7],[NSNumber numberWithInt:11],[NSNumber numberWithInt:13],[NSNumber numberWithInt:17],[NSNumber numberWithInt:19],[NSNumber numberWithInt:23],[NSNumber numberWithInt:29],[NSNumber numberWithInt:31],[NSNumber numberWithInt:37], nil];
for (int i = 0; i < 52; i++) {
Cards *card = [[Cards alloc]init];
card.face = [NSString stringWithFormat:#"%#", faces[i % 13]];
card.suit = [NSString stringWithFormat:#"%#", suits[i / 13]];
card.rankByInt = i % 13;
card.symbol = [Cards symbolForSuit:card.suit];
card.prime = [[primes objectAtIndex:(i % 13)] intValue];
[sender addObject:card];
}
[sender shuffle];
return sender;
}
Creates the _deck then _hand is filled by
[_hand addObject:[_deck objectAtIndex:0]];
[_hand addObject:[_deck objectAtIndex:1]];
[_hand addObject:[_deck objectAtIndex:3]];
[_hand addObject:[_deck objectAtIndex:4]];
[_hand addObject:[_deck objectAtIndex:5]];
[_hand addObject:[_deck objectAtIndex:7]];
[_hand addObject:[_deck objectAtIndex:9]];
returnHandRank: withString: is a very long function in the Hand class. So that is why I'm assuming they're not being retained.
Can anyone elaborate? I see it pointless to add the cards again from the _deck, it will it be the best solution?
EDIT: Added returnHandRank: withString:
+(NSString *)returnHandRank:(id)cards withString:(BOOL)returnString {
NSArray *combinations = [self returnCombinations];
cards = [self organizeCardsRankOrder:cards];
__block int maxRank = 0;
__block int maxValue = 0;
for (int i = 0; i < [combinations count]; i++) {
NSArray *splitString = [combinations[i] componentsSeparatedByString:#" "]; // splits the combination string.
NSArray *pointerArray = [[NSArray alloc] initWithObjects:
[NSNumber numberWithInt:[splitString[0] intValue]],
[NSNumber numberWithInt:[splitString[1] intValue]],
[NSNumber numberWithInt:[splitString[2] intValue]],
[NSNumber numberWithInt:[splitString[3] intValue]],
[NSNumber numberWithInt:[splitString[4] intValue]],
nil]; // turns the combinations into int values in an array.
NSMutableArray *fiveCardHand = [[NSMutableArray alloc] initWithObjects:
[cards objectAtIndex:[[pointerArray objectAtIndex:0] intValue]],
[cards objectAtIndex:[[pointerArray objectAtIndex:1] intValue]],
[cards objectAtIndex:[[pointerArray objectAtIndex:2] intValue]],
[cards objectAtIndex:[[pointerArray objectAtIndex:3] intValue]],
[cards objectAtIndex:[[pointerArray objectAtIndex:4] intValue]],
nil]; // Create the 5 card hand for the combination loop we are in, we'll now check this to see what rank it returns.
//Check for hand rank.
fiveCardHand = [self organizeCardsRankOrder:fiveCardHand];
NSArray *fiveCardHandOrganized = fiveCardHand;
int strength = [self handRankWithFiveCards:fiveCardHandOrganized];
if (strength > maxRank) {
maxRank = strength;
maxValue = 0;
}
int value = [self associateStrengthToHand:fiveCardHandOrganized andHand:strength];
if (value > maxValue) {
maxValue = value;
}
}
if (returnString) {
return [self handForStrengthWithStrength:maxRank];
} else {
return [NSString stringWithFormat:#"%i", maxValue];
}
}
There have been a few recent question involving combinations, so unless you are creating accounts we suspect there is homework afoot... No problem, let's see if we can point you in the right direction. However we cannot answer the question, not because it might be homework but because there is not sufficient information to do so.
Now I know a MutableArray simply points to the objects as opposed to holding them,
Correct so far...
so for it to lose all it's values I'm assuming the objects are being swept up by ARC.
but now completely wrong :-( You are misunderstanding how automatic memory management in Objective-C works. First forget "retain", modern ARC-based management is about ownership - whether a variable storing a reference asserts ownership over the object the reference references. When it does assert ownership the variable has the attribute strong, when it stores a reference but does not assert ownership then it has the attribute weak (there are some other ownership attributes you will come across later, they can be ignored for the moment). Object reference variables by default have the attribute strong.
Let's try an analogy:
Consider a balloon ("object"), it will float away unless it is held down; and a hand ("variable"), which holds things.
Many different hands can hold strings (references) attached to the same balloon.
If the hand holds a string tightly (strong) the ballon cannot float away.
If the string is just laying on the palm of the hand (weak) the ballon will float away unless at least one other hand is holding another string attached to the ballon tightly.
A balloon will not float away as long as at least one hand is holding a string tightly.
ARC is the breeze, it blows away balloons not held tightly.
An unannotated variable defaults to strong, so when a reference is stored in it the variable asserts ownership of the referenced object and it will not be cleared away by ARC. An instance variable of a class, or a standard (strong) property, all assert ownership. All the standard collections (arrays, dictionaries, sets) assert ownership over the objects referenced by the references stored in the collection.
Therefore, if you store a reference in an NSMutableArray the referenced object will not be cleared away by ARC as long as the reference remains in the array. If you mutate the array and remove a reference then the object referenced by it will be recycled (returned to the available memory pool) by ARC if and only if there are no other references to it stored in strong variables.
The array itself will stay around as long as a reference to it is stored in a strong variable. When there is no strong reference remaining to the array the array itself will be recycled by ARC, in the process all references stored in the array will be removed and if those references are the last strong ones to the referenced objects they too will be recycled.
Hope that helps and understanding how this works will help you find out where you are either emptying your array, or losing all strong references to the array itself; e.g. by assigning a new reference (or nil) to the variable(s) referencing the array.
Now let's look at some of your code:
NSArray *suits = [[NSArray alloc] initWithObjects:#"h",#"d",#"c",#"s", nil];
This is old style syntax, you can more easily create an NSArray using an array literal, #[ ... ]:
NSArray *suits = #[#"h", #"d", #"c", #"s"];
There are no NSMutableArray literals so you use an NSArray one an make a mutable copy: [#[ ... ] mutableCopy] or the shorter #[ ... ].mutableCopy (opinions differ on the use of the latter). There is also a literal for NSNumber objects, your code:
[NSNumber numberWithInt:41]
can simply be replaced by #41.
Using the above literals will make your code shorter and easier to read.
Now your statement:
card.face = [NSString stringWithFormat:#"%#", faces[i % 13]];
suggests a misunderstanding of how references and immutable objects work. An NSString object is immutable, once created its value will never change. The method stringWithFormat: constructs an NSString according to its format and arguments, which in this case is a single string, so you are just copying the string equivalent to:
card.face = [faces[i % 13] copy];
However a copy of an immutable object is just the original object. You know faces contains only immutable strings as you create it using string literals, so the above is equivalent to:
card.face = faces[i % 13];
Important: You can use a mutable, NSMutableString, reference as an NSString one by sub-classing, so the last step here dropping the copy is only valid if you know the reference is to an NSString object and not to an NSMutableString one.
Having used direct indexing on faces and suits you switch to long form:
card.prime = [[primes objectAtIndex:(i % 13)] intValue];
and in a few other places. All of them can be replaced by [...], e.g.:
card.prime = [[primes[i % 13] intValue];
While you uses of division (i / 13) and remainder (i % 13) are all correct you might want to consider using two nested loops to avoid them, e.g. something like:
for(int suitRank = 0; suitRank < 4; suitRank++)
{ for(int cardRank = 0; cardRank < 13; cardRank++)
{ // now use suitRank for i / 13 and cardRank for i % 13
The above is all just tidying up to make your code shorter, more readable, and less error prone. Now a more serious issue:
+(NSMutableArray*)createDeck:(id)sender {
[sender removeAllObjects];
Never do this! While id has it uses it reduces the compilers ability to check your code is correct and can result in your code going wrong when it is run for simple errors the compiler would have caught. Here sender is clearly meant to be a reference to a mutable array, declare it as such:
+ (NSMutableArray *)createDeck:(NSMutableArray *)sender
{
[sender removeAllObjects];
Later (after applying the above use of literals) you have:
NSMutableArray *fiveCardHand = #[ cards[[pointerArray[0] intValue]],
...
].mutableCopy;
//Check for hand rank.
fiveCardHand = [self organizeCardsRankOrder:fiveCardHand];
Here you:
create a mutable array
assign a reference to it to fiveCardHand
overwrite the reference in fiveCardHand with the result of organizeCardsRankOrder:
So here you appear not to have mutated the array referenced by fiveCardHand but instead changed the variable to reference a different array. You don't need to use mutable arrays to do that, you are mutating the variable holding the reference not the referenced array. Now "appear" was used here as you have not supplied the code of organizeCardsRankOrder:, maybe that method does mutate the array passed to it, if that is the case it does not need to also return it and there is no need for the assignment to the variable. So look at your code carefully here and decide whether you are mutating arrays or just variables and change it accordingly.
Finally you do not provide any declarations in the question for _deck and _hand. By naming convention you might be directly accessing the backing variable of a property (doing this is often best avoided), or accessing an instance variable, both of some unspecified class. Therefore we cannot provide any real help with these, just check that if they are connected to an instance that you are using the same instance everywhere you expect to - a common early error is to set an instance variable in one instance, try to read it from another instance, and then wonder why the value is different...
HTH, happy debugging!

-[__NSCFNumber addObject:]: unrecognized selector sent to instance [duplicate]

This question already has answers here:
How can I debug 'unrecognized selector sent to instance' error
(9 answers)
Closed 8 years ago.
I created a multidimensional array as follows:
NSMutableArray *subArray = [NSMutableArray arrayWithObjects:[NSString string], [NSNumber numberWithInt:0], [NSMutableArray array], nil];
self.dataArray = [[NSMutableArray alloc] initWithCapacity:9];
for (int i = 0; i < 9; i++) {
[self.dataArray addObject:subArray];
}
then when I try to access and change values like this
NSNumber *num = self.dataArray[0][1];
int numInt = [num intValue];
NSNumber *newNum = [NSNumber numberWithInt:numInt + 1];
[self.dataArray[0][1] addObject:newNum];
// add item to dataArray
NSMutableArray *tmpArr= self.dataArray[0][2];
[tmpArr addObject:item];
[self.dataArray[0][2] addObject:tmpArr];
but I'm getting
-[__NSCFNumber addObject:]: unrecognized selector sent to instance
what exactly is the problem, I don't understand, thanks in advance!
In the first line you are treating the object in the array as a NSNumber (which it obviously is):
NSNumber *num = self.dataArray[0][1];
And here you treat the exact same object like an NSMutableArray:
[self.dataArray[0][1] addObject:newNum];
That won't work, because that object is an instance of NSNumber.
I don't know what you achieve so I can't help you with the correct code, but that's where your problem is. Maybe you just wanted to write:
[self.dataArray[0][2] addObject:newNum];
You should probably stop to use an "inner array" as data storage and switch to using a proper subclass. Currently your code is pretty much unreadable, using proper Objects to store your values would improve it a lot.
Btw, your multidimensional array is actually just one dimensional, because you add the exact same array multiple times.
You probably want to do this:
for (int i = 0; i < 9; i++) {
NSMutableArray *subArray = [NSMutableArray arrayWithObjects:[NSString string], [NSNumber numberWithInt:0], [NSMutableArray array], nil];
[self.dataArray addObject:subArray];
}
NSNumber *num = self.dataArray[0][1];
int numInt = [num intValue];
NSNumber *newNum = [NSNumber numberWithInt:numInt + 1];
[self.dataArray[0][1] addObject:newNum]; // 3. also, possibly here
// add item to dataArray
NSMutableArray *tmpArr= self.dataArray[0][2]; // 1. here
[tmpArr addObject:item]; // 2. and here
[self.dataArray[0][2] addObject:tmpArr];
You're getting this error because the first line I marked, tmpArr is actually of type NSNumber. NSNumber is a class cluster, which is why you're seeing __NSCFNumber throw the error. All that is, is just a private subclass of NSNumber.
So the error is being thrown because you're trying to call addObject on a type of object that doesn't support it. Personally I wouldn't store more than one type of object in an array, but I don't know exactly what you're doing. Assuming you don't change the way you're storing things, what you can do is this:
NSMutableArray *tmpArr= self.dataArray[0][2];
if ([tmpArr isKindOfClass:[NSMutableArray class])
{
[tmpArr addObject:item];
}
else
{
NSLog(#"Woops, trying to add an object to something that's not a mutable array");
}
You would have to do this everytime you try to store an object into an array that you're pulling out of self.dataArray. What this does is verify that tmpArr is what you think it is.
Alternatively, you could check if it responds to addObject
if ([tmpArr respondsToSelector:#selector(addObject:)])
{
[tmpArr addObject:item];
}
The second way doesn't care what class it is, only if the method addObject can be used.

Why do we have [NSString string] when we can write [NSString new]?

Obviously I'm not just referring to NSString; there is [NSDictionary dictionary], [NSArray array], and so on. But why have all these methods when we can just send [NSDictionary new], [NSArray new], etc.?
The reason is primarily historical, because the distinction between the two is the reference count of the created object; caring about the reference count has been almost completely obviated by Automatic Reference Counting.
+string and methods like it return objects that are not owned by the caller (they are in an autorelease pool). +new, on the other hand, is one of the "four NARCs", and it does create owning references.
Previous to ARC, you would choose the one that had the memory management implications you needed in particular situation. Now, you can use whichever you prefer. There is no difference at the level of your code.
In some looping cases you may find it preferable to use +new because this still does apparently shorten the lifetime of the object as compared to +string.
To add upon Josh's good answer, when using ARC, using alloc] init] or new is preferred, because you lose the need for #autoreleasepool { ... } to relieve autorelease pressure.
Consider the following code:
for(int i = 0; i < X; i++)
{
//#autoreleasepool {
NSMutableArray* array = [NSMutableArray array];
for(int j = 0; j < Y; j++)
{
[array addObject:[NSString stringWithFormat:#"%d", j]];
}
///Do something with array.
//}
}
As X and Y grow, you will find the memory growing, and would need #autoreleasepool because the objects would only be released when the autorelease pool is drained.
Now consider
for(int i = 0; i < X; i++)
{
NSMutableArray* array = [NSMutableArray new];
for(int j = 0; j < Y; j++)
{
[array addObject:[[NSString alloc] initWithFormat:#"%d", j]];
}
///Do something with array.
}
Here the objects are released once they go out of scope and are no longer retained.
Methods like [NSDictionary dictionary], [NSArray array] and so on, return autoreleased object. Meaning that you don't have the ownership of those objects, and you don't need to worry about memory management.
When you use new or alloc you need to release those objects once you have finished using them.
This distinction is important when you're not using ARC.

NSMutableArray with size of 9

I need to have an NSMutableArray with a constant count of 9 where I can make index-specific insertions and deletions. I know that array = [[NSMutableArray alloc] initWithCapacity:9]; will declare an array with a capacity of 9, but when you get the size of the array, it returns 0.
My first attempt at a solution was to declare an array with capacity 9 (see above) and then fill it with NSNull objects. This code crashes with the error
[NSMutableArray insertObjects:atIndexes:]: array argument is not an NSArray'
- (void) setBlankArray: (NSMutableArray*)array {
for (int i = 0; i < 9; i++) {
[array insertObjects:[NSNull null] atIndexes:i];
}
}
-(void) addCurrentTile: (TileView*)aTile {
[currentTurnTilesArray insertObject:aTile atIndex: aTile.getValue-1];
}
-(void) removeCurrentTile: (TileView*)aTile {
[currentTurnTilesArray removeObjectAtIndex: aTile.getValue-1];
}
Is there a better way to accomplish it?
Not sure what you are trying to accomplish or why, but your removeCurrentTile will break it, because it will reduce the size of the array by 1. What you need to do is wrap this array with a class that guards it such that it can never never never have any other number of elements than 9.
Personally, I think what you're trying to do is silly. If you know you will always have exactly 9 slots, then you should start with a normal array, not a mutable array. It is the objects at each index that you want to mutate - not the array itself. For example, if these things were to be strings, then you would make an immutable array of 9 NSMutableString objects:
NSArray* arr = #[
[NSMutableString string],
[NSMutableString string],
[NSMutableString string],
[NSMutableString string],
[NSMutableString string],
[NSMutableString string],
[NSMutableString string],
[NSMutableString string],
[NSMutableString string]
];
Now each string can be mutated into another value, but no strings can be added or removed such as to change the length of the array.
Of course that's just an example (using strings, I mean). For maximum flexibility, this would be an NSArray of nine NSMutableDictionary objects. Now every NSMutableDictionary can contain anything, or nothing. But the number of NSMutableDictionaries will always be exactly nine, because the array itself is immutable.
You're looking for insertObject:atIndex:, or more simply addObject:.
[[NSMutableArray alloc] initWithCapacity:9] does not create an array with 9 elements.
It creates an empty array initialized with enough memory to hold 9 objects.
The purpose of this method is to allocate that much memory at once as you declare, so you can add elements to this array and system has not to allocate memory every time. This is only for optimization.
NSMutableArray reference
I just read your question, and I think I understand exactly what you need. Here is the code:
Declare a property:
#property (nonatomic, retain) NSMutableArray *myArray;
Synthesize it:
#synthesize myArray = _myArray;
Overrride its getter like this:
- (NSMutableArray *)myArray
{
if (!_myArray)
{
_myArray = [[NSMutableArray alloc] initWithCapacity:9];
for (int i = 0; i < 9; i++)
{
[self.myArray addObject:[NSNull null]];
}
}
return _myArray;
}
The "setBlankArray" method will simly set the property to nil, and next time you call the getter of the array property it will get automatically initialized with exactly what you need:
- (void)setBlankArray:(NSMutableArray *)array
{
self.myArray = nil;
}
VERY IMPORTANT: Do not write this code:
for (int i = 0; i < 9; i++)
{
[self.myArray addObject:[NSNull null]];
}
in the method just mentioned as this will make the array to contain 18 elements.
Then write the other 2 methods:
// you can also change the parameter from "id" to "TileView *"
- (void)addCurrentTile:(id)sender
{
NSInteger tileIndex = 1; // replace 1 with ((TileView *) sender).getValue - 1
[self.myArray replaceObjectAtIndex:tileIndex
withObject:sender];
}
// you can also change the parameter from "id" to "TileView *"
- (void)removeCurrentTile:(id)sender
{
NSInteger tileIndex = 1; // replace 1 with ((TileView *) sender).getValue - 1
[self.myArray replaceObjectAtIndex:tileIndex
withObject:[NSNull null]];
}
But, DO NOT FORGET to replace "id" with "TileView *", and TO SET the value of tileIndex to "((TileView *) sender).getValue - 1".
Hope this all makes sense, and is helpful for you.
Best regards

Storing objects in an array in objective c

I'm trying to store 25 objects in an array
for (int iy=0; iy<5; iy++) {
for (int ix=0; ix<5; ix++) {
TerrainHex *myObject = [[TerrainHex alloc] initWithName:(#"grassHex instance 10000") width:mGameWidth height:mGameHeight indexX:ix indexY:iy];
myObject.myImage.y += 100;
[TerrainHexArray addObject:myObject];
[self addChild:(id)myObject.myImage];
}
}
NSLog(#"Terrain array: %u", [TerrainHexArray count]);
The log is coming back as zero though.
In the .h file I have
#property NSMutableArray *TerrainHexArray;
And in the .m file I have..
#synthesize TerrainHexArray;
I just tried what someone suggested below, which is..
NSMutableArray *TerrainHexArray = [[NSMutableArray] alloc] init];
But it's just giving me a warning saying expected identifier.
It's almost certain that TerrainHexArray does not exist when you're doing the addObject calls and the NSLog. You say you tried adding the alloc/init after someone suggested it, which indicates you don't understand object management in Objective-C.
I'd suggest you step back, find a book on Objective-C, and read at least the first few chapters (up through the discussion of alloc/init et al) before you attempt any more coding.
Incidentally, it's standard C++/Objective-C coding practice (except in Microsoft) to use identifiers with a leading lower case character for instance names, reserving leading caps for types/class names.
What is TerrainHexArray? It looks like a class name, not an instance of an array. If you create a mutable array, then you can add the items to the array.
NSMutableArray *hexArray = [[NSMutableArray] alloc] init];
for (int iy=0; iy<5; iy++) {
for (int ix=0; ix<5; ix++) {
TerrainHex *myObject = [[TerrainHex alloc] initWithName:(#"grassHex instance 10000") width:mGameWidth height:mGameHeight indexX:ix indexY:iy];
myObject.myImage.y += 100;
[hexArray addObject:myObject];
[self addChild:(id)myObject.myImage];
}
}
NSLog(#"Terrain array: %u", [hexArray count]);