NSString * str; ///< Global string.
/// Some class method
-(void) foo:(NSString*) localStr
{
str = [[NSString alloc] initWithString:localStr];
}
I’m using ARC – so I can’t manually deallocate the NSString* str if not nil.
I understand that ARC runs in compile-time, so it would not know if to deallocate the NSString before allocating the NSString if foo is called twice.
Using ARC, it will automatically dealloc
strif it is pointing to a string with no other references and you set it to a new string object. You don’t need to worry about managing the old string when you are setting a new value.ARC stands for Automatic Reference Counting and it takes care of calling
retainandreleasefor you at the appropriate times (such as when you change the value ofstr). In fact, you can’t even manually call those functions anymore, but the same things is taking place “behind the scenes”.As an aside, you say “I can’t manually deallocate the NSString* str if not nil.”. What you normally do to deallocate an object when using ARC is to just set all of the references to it to
nil. So in this case, when you want to deallocate the string (assuming thatstris your only reference to it) you simply need to setstrtonil:str = nil;. Keep in mind however, as I said above, that you do not need to do this in order to setstrto a new value. ARC is smart enough to take care of both at the same time.Another aside: You have the following line of code:
If you actually intended to make a copy, you can replace this with:
It is a little shorter and easier to understand. More likely, you don’t need an actual copy and you can just keep a reference to the existing string, so you can use: