[英]Simple Delegate Between View Controller and UIView Isn't Working
[英]UIView isn't released. Calling delegate with self, and using UIView commitAnimations adds retain count
我有一個視圖作為子視圖添加到viewcontroller中。 子視圖具有委托方法,並且將視圖控制器作為其委托。 子視圖具有動畫,並在動畫完成時調用委托方法。
問題是,當導航控制器從視圖中刪除視圖控制器時,子視圖不會被釋放。 可能是因為它的發布計數大於0。 當在子視圖動畫完成之前將視圖控制器從視圖中移除時,子視圖嘗試調用委托(這是不再存在的視圖控制器)方法,並且我得到了EXC_BAD_ACCESS。
也許一些示例可以澄清問題;):
風景
- (void)somefunction {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(viewDidAnimate:finished:context:)];
[UIView setAnimationDuration:0.3];
self.frame = CGRectMake(0, 320, 320, 47);
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView commitAnimations];
}
-(void)viewDidAnimate:(NSString *)animationID finished:(BOOL)finished context:(void *)context{
if (self.delegate != NULL && [self.delegate respondsToSelector:@selector(viewWasAnimated:)]) {
[delegate viewWasAnimated:self];
}
}
視圖控制器
- (void)viewDidLoad{
[super viewDidLoad];
MYView *myview = [[MYView alloc] init];
myview.delegate = self;
[self.view addSubview:myview];
[myview release];
}
- (void)viewWasAnimated:(MYView *)view{
}
我發現
[UIView commitAnimations];
行view的retainCount為2,並在
[delegate viewWasAnimated:self];
發布計數為3。因此,這可能就是為什么不發布視圖的原因。 我知道我不應該查看保留計數,但不知道還要做什么。
您的視圖未取消分配,因為UIView
beginAnimation
塊會在整個動畫期間保留該視圖。 因此,如果可以在動畫過程中釋放控制器,則可以從控制器的視圖中的dealloc和animationDidStop:
方法中刪除UIView
,如果是,則檢查superview是否等於nil,然后不發送消息
-(void)viewDidAnimate:(NSString *)animationID finished:(BOOL)finished context:(void *)context{
if (self.superview != nil && self.delegate != NULL && [self.delegate respondsToSelector:@selector(viewWasAnimated:)] ) {
[delegate viewWasAnimated:self];
}
}
您可以采取的另一種方法是取消UIView
動畫,但這並不那么直觀。
在UIViewController
的dealloc方法中
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView commitAnimations];
這將取消當前動畫。 並且您將在animationDidStop
消息中收到finished == NO
(void)viewDidAnimate:(NSString *)animationID finished:(BOOL)finished context:(void *)context{
if ( finished && self.delegate != NULL && [self.delegate respondsToSelector:@selector(viewWasAnimated:)] ) {
[delegate viewWasAnimated:self];
}
}
首先,我想這是一個錯字,但:
[self.view addSubview:adview];
應該
[self.view addSubview:myview];
關於您的問題:
1-放入MYView * myview; 在你的viewcontroller.h中
2-在釋放ViewController之前,請致電:
[myview removeFromSuperView];
這應該重新分配您的子視圖。(如果沒有其他保留)
祝好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.