Double exemption when this should not happen

I am really puzzled by this. I believe that I manage memory correctly, but code execution assumes that I release the object twice. Here is the code, and then I will explain what happens.

@protocol SomeDelegate <NSObject>
@required
- (id)initWithCols:(NSUInteger)Cols Rows:(NSUInteger)Rows;
@end


@interface SomeObject : NSObject <SomeDelegate> {
}
- (id)initWithCols:(NSUInteger)Cols Rows:(NSUInteger)Rows;
@end


@interface Layout : UIView {
  id<SomeDelegate> someDelegate;
}
@property(retain) id<SomeDelegate> someDelegate;
- (id)initWithFrame:(CGRect)aRect Cols:(NSUInteger)Cols Rows:(NSUInteger)Rows;
@end


@implementation Layout
@synthesize someDelegate;
- (id)initWithFrame:(CGRect)aRect Cols:(NSUInteger)Cols Rows:(NSUInteger)Rows {

  if(self = [super initWithFrame:aRect]) {
    cols = Cols; 
    rows = Rows;
    id<SomeDelegate> delegate = [[SomeObject alloc] initWithCols:cols Rows:rows];
    [self setSomeDelegate:delegate];
    //[delegate release];
  }
  return self;
}

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

@end

Now, when I uncomment "// [delegate release]; line in the constructor of the Layout class, then I get the error" EXC_BAD_ACCESS "and the application crashes when I try to dealloc. I tracked the failure to issue the someDelegate object in the dealloc method of the Layout class. If you leave a comment , then the application is working fine.

Can someone explain why this is happening, as it seems to contradict everything I read about memory management in Objective-C.

, , . - SomeObject, ?

.

+3
3

-, , , .

NSZombieEnabled ( , "", NSZombieEnabled, YES).

dealloc delagate, (, [super dealloc]!) - , delagate , .

release/ , , , , , .

: Objective C/ Cocoa , :

- (id)initWithFrame:(CGRect)aRect cols:(NSUInteger)Cols rows:(NSUInteger)Rows;

ivar , , ivar , , _ Apple, - Apple:

  id<SomeDelegate> _someDelegate;

@synthesize someDelegate = _someDelegate;

Apple seters/getters init/dealloc, :

_someDelegate = [[SomeObject alloc] initWithCols:cols Rows:rows];
+3

, .

, , ...

-release , - , , - , , . , , .

, , - -release -dealloc, Zombies. .

"" "NSZombie" , ( " " ).

+2

The problem was that MutableArray was deep in the subclass that was created using factory (autoreleased), but I also released. Unfortunately, the accident does not indicate which inherited dealloc was crashing and simply stopped at the first redefined dealloc.

The zombies helped a bit in that he told me that the array was the culprit, but not much more. I think NSZombie is more suitable and requires more experience to make full use of it.

0
source

Source: https://habr.com/ru/post/1711523/


All Articles