Reputation: 765
I just wrote some code. It has my own custom made class. In that custom made class called 'WonderfulNumbers' I have a method that looks like this
- (NSString *)storedNumberAsString {
NSString *stringToReturn = [[NSString alloc]initWithFormat:@"Hello World"];
return [stringToReturn autorelease];
}
I obviously then #import "WonderfulNumbers" into the main and etc then in my main I have an IBAction. it reads like the following
-(IBAction)displaySomeText:(id)sender {
WonderfulNumbers *myNumber = [[WonderfulNumbers alloc]init];// Step 1
NSString *numberString = [myNumber storedNumberAsString];// Step 2
[textView insertText:numberString];// Step 3
//textView is a variable of NSTextView.
[myNumber release];// Step 4
}
I get the step by step process, and the logic behind this. What I like to know and try to reassure to my self is what exactly is happening at step 2.
I understand Step 1, 3 and 4.
But step 2, I crated an NSString variable called 'numberString' and it obviously holds the object called 'myNumber' with the method described above applied to it. Makes sense.
What I want to know is, I never allocated or initialized the 'numberString' object of NSString class. How am I able to then use it. I know I don't release it since it's never allocated .. but did I initialize it by just doing [myNumber storedNumberAsString]; ?
A slight explanation would be awesome. Thank's to those that reply.
P.S. I know that everything in objective-c is an object but just for the sake of this argument, since 'numberString' is not technically "created by allocate and init" is it right to call that a variable?
I think I know the differences between the two but just want reassurance.
Thanks.
Upvotes: 0
Views: 72
Reputation: 42149
You are initializing NSString *stringToReturn
to the return value of [myNumber storedNumberAsString]
. Inside storedNumberAsString
you can see that it returns an NSString
reference, properly allocated and all, so it's fine to use.
The key here is autorelease
, which causes the object to be released automatically “sometime later” (actually when the topmost autorelease pool is released, which, unless you changed it yourself, tends to happen after each iteration of the event loop).
The convention in Objective-C is that if you alloc
or retain
an object, or get an object from a method whose name begins with new
, copy
, or mutableCopy
, you are responsible for releasing it. Otherwise you can assume it will be released by someone else (e.g., later via autorelease
). Since storedNumberAsString
does not begin with new
, copy
, or mutableCopy
, you don't need to release it. Meanwhile the implementation of storedNumberAsString
must ensure that the object it alloc
s gets released -- in this case that is done by calling autorelease
on it.
Upvotes: 2