I’m new to objective-c and I always have problem with global variable . I don’t know where to initialize them . My problem is with an NSString . I wrote this code –
in .h
NSString *session ; // i also @property(retain,nonatomic) and synthesize ...
in viewDidLoad , ‘
session=@"HEllo";
and in
-(IBAction) showInformations:(id)sender;
{
NSLog(@" informations ok");
NSLog(@"my sesison : %@ ",session);
}
But I have a crash in show information :/ session is empty I think . Help please
There is a huge difference between the above two statements. The first one just assigns
hellotosession. Here the stringhellois autoreleased, sosessionis not valid when you tap the button, as you have not retainedsession. But in 2nd lineselfis used. Whenselfis used, it is not just a simple assignment, it is actually a call to accessor method. Here you have usedretainin property declaration. So whenselfis used, the setter forsessionis called which retains it. Sosessionis valid when you tap the button.The summery is use right property and use
selfto avoid many memory problems.EDIT: As pointed by fluchtpunkt, this explanation is not valid for string literals. I was out of my mind that string literals are special when writing this.