Why are objects not freed in the dealloc method?

I have a problem understanding Objective-C and ARC.

As I understand it, strong pointers will be automatically canceled for you, so you do not need to think about it (canceled in the dealloc method or after the last use of the object?).

So, I wrote a small application with two viewControllers and NavigationController, which goes into one view and then returns.

The dealloc method was called, but the property that I set in the viewDidLoad method was not released, it still points to some object.

code: The first viewController has a button that, by clicking on it, executes a segue on another viewController. There is no code there.

SecondViewController.m

@interface SecondViewController () 
@property (nonatomic, strong) NSString *myString;
@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@", _myString);
    _myString = @"it works";
}

- (void)dealloc {
    NSLog(@"%@", _myString);
    // and now it is deallocating the _myString property ???
}

@end

Then I tried to do one more thing.

, , . , , .

  • dealloc, niled

  • viewDidLoad, dealloc.

, . ?

secondViewController:

@interface SecondViewController ()
@property (nonatomic, strong) NSString *myString;
@property (nonatomic, weak) NSString *test;
@end

@implementation SecondViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%@", _myString);
    _myString = @"it works";
    _test = _myString;
}

- (void)dealloc
{
    NSLog(@"%@", _test);
}

@end
+4
2

dealloc. dealloc, .


, , , , .

+3

weak ...

:

@interface ObjectWithStrongRef : NSObject

@property (strong) NSString *ref;

@end

@interface ObjectWithWeakRef : NSObject

@property (weak) NSString *ref;

@end

ObjectWithWeakRef , , ObjectWithStrongRef, ref , , ref , ref .

int main(int argc, const char * argv[]) {
    ObjectWithWeakRef *weak = [[ObjectWithWeakRef alloc] init];

    @autoreleasepool {
        ObjectWithStrongRef *strong = [[ObjectWithStrongRef alloc] init];
        strong.ref = [NSString stringWithFormat:@"Hello %@", @"World"];
        weak.ref = strong.ref;

        NSLog(@"Weak.Ref = %@", weak.ref);
    }

    NSLog(@"Weak.Ref = %@", weak.ref);
}

, ref . Objective-C , , stringWithFormat:, .

NSLog strong.ref , , weak.ref, , "Hello World".

NSLog @autoreleasepool, strong, ( NSLog ObjectWithStrongRef dealloc d . ). strong , @autoreleasepool, - , , - weak , ( , strong ).

, NSLog Weak.Ref = (null).

+3

All Articles