I have a problem understanding the Objective-C and the ARC.
As I understood the strong pointers will be dealloced automatically for you, so you don't have to think about it (dealloced in dealloc method, or after the last time the object was used ?).
So I wrote a little app, with 2 viewControllers and a NavigationController, which enters one view and then goes back.
The dealloc method was called, but the property, which I set at viewDidLoad method, wasn't deallocated, it is still pointing to some object.
Code: The first viewController has a button, which by pressing it, performs a segue to another viewController. 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 another thing.
The idea was to create a weak pointer, which points to the same memory address, as the strong pointer. I though, that the weak pointer should be nil in any case.
Since the dealloc method is called, all weak pointers should be niled
Since the strong pointer was used only in viewDidLoad, it should be deallocated way before the dealloc method.
The problem is, it is not deallocated. Why ?
Code for 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
@"it works"
will never be deallocated because it is never allocated in the first place; it is a part of the executable image. Secondly, even if the object were deallocated, messaging a deallocated object exhibits undefined behavior and is not guaranteed to cause a crash or other symptom. – bbumstringWithFormat:
in my answer. – nhgrif@"..."
is actually created at compile time and is a part of the app's executable. It is mapped into memory along with the rest of the app's data (and code) and, thus, it isn't part of the allocation heap of the app. Said objects don't do anything when released or retained and they are never deallocated because there is no allocation in the first place. Using NSString (or other framework classes) is oft confusing for this, and other (see tagged pointers), reasons. Always use your own subclass ofNSObject
when doing these kinds of learning exercises! – bbum