Reputation: 717
I have a static variable and assign some object to this several times like this..
@interface DetailViewController ()
@end
// static varable for Entry
static DirectoryEntry *dirEntry;
@implementation DetailViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
// init entry
dirEntry = [[DirectoryEntry alloc]init];
NSLog(@"%@ ",dirEntry);
}
My question is that why it's result of NSLog showing is different than each others...?
every time when it gets loaded, it has different address then, where is the previous obj that static pointer pointed to no that it has different address which means the previous object got distorted?
Thank you in advance .
Upvotes: 1
Views: 80
Reputation:
The static
modifier doesn't work that way.
When applied to a global variable like you're doing here, the static
keyword just causes the variable name to only be visible within the current file. (This means that another file that declares a global variable called dirEntry
will end up with a separate variable, not another reference to this one.)
If you want to only initialize this variable once, you'll need to ask for it explicitly:
static DirectoryEntry *entry = NULL;
...
if (entry == NULL) {
entry = [[DirectoryEntry alloc] init];
}
Upvotes: 2
Reputation: 13713
It shows different results since you allocate a new object every time viewDidLoad
is called.
The fact that dirEntry
is static does not make allocations to be allocated in the same address every time.
Once you reassign a new allocation the previous address is lost (if you use ARC then it will be deallocated for you) unless you assign it to another pointer variable before the new allocation.
Upvotes: 1