Nina
Nina

Reputation: 1679

NSString alloc / release / retain

a is an instance of NSString. I thought if I print a string after releasing it, it will crash the app. Instead it returned proper value assigned to it. My question is, shall we get the value of an object even after releasing it? If not, why I am able to see the value of a, even after it is deallocated?

.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    NSString *a;
}

@end

.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    a=[[NSString alloc]initWithString:@"abc"];

    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    NSLog(@"String %@",a);
    [a release];
    NSLog(@"release %@",a);
    [a retain];
    NSLog(@"retain %@",a); 
}

Output:-

2012-08-24 14:15:49.501 a[1176:f803] string abc
2012-08-24 14:15:53.404 a[1176:f803] release abc
2012-08-24 14:15:55.325 a[1176:f803] retain abc

Upvotes: 4

Views: 333

Answers (2)

beryllium
beryllium

Reputation: 29767

@"abc" is a constant, so it will never be released

feel the difference:

a = [[NSString alloc] initWithFormat:@"%d", 123];

it gives for me crash or release main output since it refers to some chunk of memory

Upvotes: 3

waldrumpus
waldrumpus

Reputation: 2590

Releasing any object means that the caller is done with it. After the release, the results of trying to access the object are undefined - could be a crash, could be that someone else is retaining the object and it works without crashing, could be something else entirely.

So, if you release an object, you should not try to access it afterwards in the same scope where you previously retained (init'ed, copied) it.

Upvotes: 3

Related Questions