Luca
Luca

Reputation: 20919

NSString memory management issue: message sent to deallocated instance

I have an NSString declared like this :

.h:

@interface ViewController : UIViewController

{

        NSString * aString;

}
@property(nonatomic,copy)NSString *aString;

.m :

@synthesize aString;

......

aString=[[NSString alloc]init];
aString=@"Hello World";

NSLog(@"%@",aString);//The app crashes here

The app crashes with this stack trace:

-[CFString respondsToSelector:]: message sent to deallocated instance

Upvotes: 2

Views: 1557

Answers (1)

graver
graver

Reputation: 15213

remove the line:

aString=[[NSString alloc]init];

and set values to the property:

self.aString=@"Hello World";

Doing: aString=@"Hello World"; means you are setting value to the instance variable, without using the accessor methods of the property, then you are responsible to the memory management and it's more complicated. Get the value by: self.aString also.
P.S. Always work though properties, almost never use the instance variables, (only in the dealloc method release the ivar, otherwise if you are not good at memory management you will always have problems, but properties do everything for you)

Upvotes: 8

Related Questions