Suppose I have two classes. In the first one I declare this in Class1.h
@interface Class1 : UIViewController {
NSString *myString;
id myObject;
}
On the second class I go beyond that I declare it like
@interface Class2 : UIViewController {
NSString *myString;
id myObject;
}
@property (nonatomic, retain) NSString *myString;
@property (nonatomic, retain) id myObject;
and then I @synthesize myString, myObject on Class2.m
Then, on my main program, I create two objects: one based on Class1 and another one based on Class2.
What effect the @property of class2 will have? Will every value assigned to both values on Class2 be always retained? If so, do I need to “release” them? How?
Thanks.
Please read Declared Properties section of The Objective-C programming language
for a full explanation on properties 😉
In Class2:
In this case you set
retainattribute to your property it is supposed to be retained in the implementation. This is done automatically when you synthesize a property.This means that you should have
and everything should be fine
In Class1, you don’t have properties so myString and myObject is not visible from outside. But this does not mean that you shouldn’t release them. It depends on the way you initialize them and/or if you send retain messages to them.
BTW, if you set
assigna property you don’t release it, just set it to nil in the dealloc method. If you setcopyto it then you must release it.EDIT
You said: *But suppose I have this *
and
? I am already releasing myView… do I have to release it again???
First, since you have your property defined that way, you should have dealloc method as:
So, the answer is NO you should not release it but actually is not correct.
Please take a look:
later in dealloc method
This is the correct way: (Use your properties 😉 )
even if it is 2 there is no problem because when self.view is deallocated its subviews also will be released. Hence self.myView retainCount will become 1 again later when self is deallocated.
What is the difference?
Suppose self.myView is also retained by other object X and with the former approach, X’s view will be pointing to an invalid object, because it was already released.
Hope it helps
EDIT2
As bbum’s indication, this is a mini-mini-short tutorial on properties:
when you have
and you @synthesize them
is like having the following setters:
(this means that if you assign directly an object you have to make sure is something equivalent to above setters, from the memory management point of view)
and your dealloc method should be something like:
When setting your ivars
for example, inside of init: