Objective-c - Retain Count when I change View go to zero
I declared a UIImage and a UIImage View in one viewcontroller like this:
In the .h file:
UIImageView* itemImageView;
开发者_如何学PythonUIImage* itemImage;
@property (nonatomic, retain) UIImage* itemImage;
@property (nonatomic, retain) UIImageView* itemImageView;
In the .m file:
@synthesize itemImage, itemImageView;
In another view, I set its value:
UIImage *image = [UIImage imageNamed:@"name1.png"];
imgView.itemImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 82, 166)];
imgView.itemImageView.image = image;
[self.parentViewController.view addSubview:imgView.itemImageView];
[self dismissModalViewControllerAnimated:YES];
Inside this method, the retain count of itemImageView is 2.
But when I go back to the view where I put the property and the synthesize, the retain count is 0 and I cannot access the object.
Any idea whats happening?
Your code here looks ok. (Aside from a memory leak) You're assigning an ImageView with a retain-count +1 to itemImageView, which will increase it to two. You need to call release on your ImageView after setting it to itemImageView:
UIImageView* iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 82, 166)];
imgView.itemImageView = iv;
[iv release];
However, this doesn't fix your problem (it will even make it worse..) Can you show more code? Have you tried stepping through it with the Debugger?
UIImageView* itemImageView;
...
@property (nonatomic, retain) UIImageView* itemImageView;
...
imgView.itemImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 82, 166)];
This causes a double retain since alloc
increases the retain counter by 1, and so does the retain
setting of the @property
.
The general pattern for setting properties is like so:
.h:
SomeClass* someClass;
...
@property (nonatomic, retain) SomeClass* someClass;
.m:
SomeClass* temporarySomeClass = [[SomeClass alloc] init];
self.someClass = temporarySomeClass;
[temporarySomeClass release];
...
Here, we're using a temporary variable to hold the object we alloced, and then doing a release right after.
You'll see that in the Apple example code for sure.
your problem is with this line:
[self.parentViewController.view addSubview:imgView.itemImageView];
this should most likely be edited as such:
[self.parentViewController.view addSubview:self.parentViewController.itemImageView];
this leads to the question of whether imgView is really equivalent to parentViewController.view. if you wanted it to be, then you need to figure out where that got assigned and see where you messed that up. if not, then theres no point in using it for anything but a temporary container to build ur objects in before assigning it.
edit: the memory leak is a separate issue yes, but im not sure how u declared imgView in the method so i left that for you to solve :)
精彩评论