I have an NSString
property:
.h file
@property (nonatomic, retain) NSString *str;
.m file
@synthesize str;
What is the retain count
of str
without alloc
/init
? Can I [str release]
in a method?
I have an NSString
property:
.h file
@property (nonatomic, retain) NSString *str;
.m file
@synthesize str;
What is the retain count
of str
without alloc
/init
? Can I [str release]
in a method?
I am assuming your new to the concept of memory management, so I would advise to have a read of the apple docs around memory management before you continue with your development.
Basic Memory Management Rules
- You own any object you create.
- You can take ownership of an object using retain.
- When you no longer need it, you must relinquish ownership of an object you own.
- You must not relinquish ownership of an object you don't own.
I will refer you to the Memory Management Policy in the apple docs for a good understanding of memory management
So when you have read the apple docs you will fully understand what is going on in your code, but if you don't this is what is wrong. You can not release an object that you don't have ownership of. This violates point 4 of the Basic memory management rules in the apple docs. To take ownership of this object you must do str = [[NSString alloc] init];
(This is not needed with ARC) in your .m file.
My recommendation though would be to read up about ARC it is a lot better then handling the memory management yourself. As you would no longer have to do things such as [str release];
once you wanted to relinquish ownership of the object as it is done automatically.
You cannot release an object that has not yet been allocated.
Use ARC where possible, and read about changes to Objective-C in the past 2 years: it is no longer necessary to synthesize variables declared in .h in your .m
You shoudn't release
an object that has not yet been allocated. But if you do it it means you are sending a message to a nil
object. That is safe because a message to nil
does nothing and returns nil
, Nil
, NULL
, 0
, or 0.0
.
Yes you can release this object. Whenever you send alloc, copy, new, retain
any of these message to an object. It's retain count increased by 1. And you become the owner of that object. So you must release the object to relinquish the ownership.
And when you use ARC the compiler do it for you. Hope it helps.
As its a retained
property you can do self.str=nil;
instead of [str release]
safely.
You can not do [str release]
as we can release
only what we alloc
and init
by ourself and its not init
yet.