Reputation: 1921
Hi all i have a problem in understanding the concept of retain in following example.i know about usage of retain...but confused here..
i have 2 classes View1 and View2
here is method of View1
-(IBAction)callingView2
{
view2 *view=[[view2 alloc] init];
[self.navigationController pushViewController:view animated:YES];
NSString *ss=[[NSString alloc]initWithString:@"Hi friend"];
[view callingToRetain:ss];
[ss release];
[view release];
}
and in view2 i have 2 methods and str is a string(not allocated)
-(void)callingToRetain:(NSString*)s
{
//[s retain]; //it is not effecting my program
str = s;
}
//And then printing it on a button click after reaching to view2
-(IBAction)print
{
NSLog(@"string = %@",str);
}
The rules says that i should retain the string if i have to use it later, but here it's working without retain.....
I thing this is due to str = s;
because it is retaining to MAX_VALUE, but i am not sure...
if this is the problem then does it effects the memory leak concept ?
Any suggestions?
Upvotes: 0
Views: 99
Reputation: 56467
Even if it's working without retain
, you should use it (or better yet, copy
it). That's the rule. That doesn't mean it will work in the future, or with other calls.
Also, don't forget to release
it on dealloc
.
Upvotes: 1
Reputation: 34185
The rule only says you need to retain if you need to use an object later.
It does not say if you fail to retain correctly, it will definitely crash.
Most often, not retaining correctly leads to a crash sooner or later. But your code is an exception, because the string you used was just a constant string known at a compile time.
What's going on is this. Suppose you perform the following operation:
NSString* s=@"foo";
NSString* ss=[[NSString alloc] initWithString:@"foo"];
This in fact makes ss
equal to s
. As an optimization, the Cocoa runtime does not create a separate NSString
instance.
And this object s
is a compile-time NSString
, which effectively behave like an infinitely-retained object.
That's why your code didn't crash. However, Apple can change the Cocoa runtime implementation in the next version of the OS so that your code does crash.
The point is that you should follow the rule. If you follow the rule, it doesn't crash even in a future version of the OS. If it doesn't, it might not lead the crash immediately, but it eventually will.
Upvotes: 5