KopBob
KopBob

Reputation: 1151

Store UIImageViews in NSMutableDictionary

I have simple question. This is my header file :

#import <UIKit/UIKit.h>

@interface FirstFaceController : UIViewController

@property (nonatomic,retain) NSMutableDictionary *face1Layers;

@end

This .m, here i init my Dictionary and put where UIImageView :

#import "FirstFaceController.h"

@implementation FirstFaceController

@synthesize face1Layers;



-(void) dealloc {
    [face1Layers release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.face1Layers = [NSMutableDictionary dictionary];
    [self.face1Layers setObject:
            [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic.png"]] 
                 forKey:@"pic"];

    [self.view addSubview:[self.face1Layers objectForKey:@"pic"]];
    if ( [[face1Layers objectForKey:@"pic"] superview] == nil ) {
         //....
    }
}

Then i call [[face1Layers objectForKey:@"pic"] superview] i have "EXC_BAD_ACCESS". Why?

Upvotes: 0

Views: 1768

Answers (2)

Lorenzo B
Lorenzo B

Reputation: 33428

Try to do this:

NSMutableDictionary* tempDict = [[NSMutableDictionary alloc] init];
self.face1Layers = tempDict;
UIImageView* picView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic.png"]];
[self.face1Layers setObject:picView forKey:@"pic"];
[picView release];
[tempDict release];

Do not create and insert yours NSMutableDictionary and UIImageView throught a single line of code because you have leaks.

In the first case, if you do the following you have a retain count of two. face1Layers has a retain policy.

self.face1Layers = [[NSMutableDictionary alloc] init];

You can avoid this splitting the code as I explained before or send an autorelease message to the initialized object.

In the second case, when you add an object in NSDictionary or NSArray (and theirs subclasses), these classes retain added objects.

Hope it helps.

Upvotes: 1

Bob de Graaf
Bob de Graaf

Reputation: 2722

Well, I think there are a couple of things wrong here:

  1. You never allocate the dictionary as in NSMutableDictionary alloc init
  2. The UIImageView is allocated but never released. I would allocate before setting it as object, and then add it, and then release it

Upvotes: 0

Related Questions