Infinite Possibilities
Infinite Possibilities

Reputation: 7466

Memory problem with properties in objective-c

UIImage *image = [[UIImage alloc] initWithData:data]; ((YKSubCategory *)[_subCategories objectAtIndex:connection.tag - 1]).menuImage = image; [image release];

Here is the code I've written. The data is exists and the designed image is created. (I've tested it with an imageview and the image appears). The problem comes when I try to set the menuImage property. It will not be set. I don't know why. So the value of the menuImage property remains nil. Here is the property definition:

@property (nonatomic, retain) UIImage *menuImage;

What can be the problem?


Edit:

I've divided the code for the request of walkytalky. Here is the code I've written:

UIImage *image = [[UIImage alloc] initWithData:data];
YKSubCategory *subCategory = (YKSubCategory *)[_subCategories objectAtIndex:connection.tag - 1];
subCategory.menuImage = image;
[image release];
[_tableView reloadData];

So now the funny thing is that the subCategory variable is the variable what I expect. Then after I set the menuImage property then the variable for this property is set. I can see in the debugger, but in the array isn't set. What is this?

Upvotes: 0

Views: 65

Answers (1)

walkytalky
walkytalky

Reputation: 9543

(i) Have you @synthesize-d menuImage?

(ii) Can you break up the setter line to first get the YKSubCategory object and test it exists and is what you expect?

YKSubCategory* target = (YKSubCategory*)[_subCategories objectAtIndex:connection.tag - 1];
NSLog("subcategory target = %@", target);
// other tests here
target.menuImage = image;

Otherwise, I don't think we have enough info to solve this. What does menuImage look like immediately after setting?


EDIT: when you say "in the array isn't set", do you mean that the actual object in the array differs from the one you've just set right there and then? Or that when you come back to the array when loading the table data the menuImage is no longer set? Or that it just doesn't show in the table?

The first seems impossible on the face of it, so let's think about the second and third.

If menuImage has been reset by the time you come back to it, there must be some code setting it somewhere. This may not go through the property accessor, but for starters you might explicitly implement the setter to log the changes:

- (void) setMenuImage:(UIImage*)newImage
{
    if ( newImage != menuImage )
    {
        NSLog(@"Changing menuImage from %@ to %@", menuImage, newImage);
        [newImage retain];
        [menuImage release];
        menuImage = newImage;
    }
}

Another possibility is that the actual YKSubCategory object in the array has changed, or even that the arrays are different, so check that the pointers are the same in both locations.

On the other hand, if the menu image ivar is set, but it's not showing up in the table, you need to check your drawing code.

Upvotes: 1

Related Questions