简体   繁体   English

在iOS ARC中,我的递归函数使用EXC_BAD_ACCESS使应用程序崩溃

[英]In iOS ARC my recursive function crashes application with EXC_BAD_ACCESS

Following code of mine generates crash in ARC mode: 我的以下代码在ARC模式下会导致崩溃:

MxTextField.m

+enableAllTextFields:(BOOL)enable InViews:(__weak UIView*) view
{

   @try
   {
      NSArray* textFields = view.subViews;

      for(int idx = 0; idx < textFields.count; idx++)
      {
         __weak UIView* view = [textFields objectAtIndex:idx];

         if(view.subViews.count > 0)
            [MxTextField enableAllTextFields:enable InView:view];
         else
            NSLog(@"No SubViews");

         if([view class] == [MxTextField class])
            [(MxTextField*) view setEnabled:enable];
      }

   }
   @catch(NSException exception)
   {
      NSLog(@"%s : %@",__func__,exception);
   }

}

After Some Loop on the execution of this function It crashes by showing breakpoint at the end of the function saying EXC_BAD_ACCESS. 在执行此函数的Some Loop之后。通过在函数末尾显示断点EXC_BAD_ACCESS来崩溃。 Can anyone help me out that what goes wrong in this implementation? 谁能帮我解决此实施中出了什么问题?

Any help will be thankful. 任何帮助将是感激的。

The problem could be the method adopted for iteration and also try-catch is not a good practice, use fast-enumeration for faster and reliable result . 问题可能是迭代所采用的方法,try-catch也不是一个好习惯,请使用快速枚举以获得更快,更可靠的结果。 The below code could resolve your problem 以下代码可以解决您的问题

+(void)enableAllTextField:(BOOL)enable inView:(UIView *)contrainerView
{
    for (UIView *subview in contrainerView.subviews) {
        if(subview.subviews.count>0)
             [MxTextField enableAllTextField:enable inView:subview];
        else if ([subview isKindOfClass:[MxTextField class]]) {
             MxTextField *textField = (MxTextField *)subview;
             [textField setEnabled:enable];
        }
    }
}

Putting aside many other problems the only reason for a crash that I can see from the posted code is that your method is supposed to return an object but does not do so. 撇开其他许多问题,从发布的代码中可以看到崩溃的唯一原因是您的方法应该返回一个对象,但不会这样做。

Explanation: While it's not common to leave out the return type in Objective-C it's perfectly legal. 说明:虽然在Objective-C中省略返回类型并不常见,但这是完全合法的。 It means that the method returns an object of type id. 这意味着该方法返回一个id类型的对象。

Since your method lacks a return statement the returned value is undefined. 由于您的方法缺少return语句,因此返回的值是不确定的。 This confuses ARC and probably makes it autorelease the random value in the return register which, eventually, leads to the crash. 这会混淆ARC,并可能使其自动释放返回寄存器中的随机值,最终导致崩溃。

Here's a proper version of your method: 这是您方法的正确版本:

+ (void)forAllTextFieldsIn:(UIView *)view setEnabled:(BOOL)enabled
{
    if ([view isKindOfClass:[MxTextField class]])
        [(MxTextField *)view setEnabled:enabled];

    for (UIView *subview in view.subviews)
        [self forAllTextFieldsIn:subview setEnabled:enabled];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM