Reassign global NSString pointer

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 str if 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 retain and release for you at the appropriate times (such as when you change the value of str ). 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 that str is your only reference to it) you simply need to set str to nil : str = nil; . Keep in mind however, as I said above, that you do not need to do this in order to set str to 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:

str = [[NSString alloc] initWithString:localStr];

If you actually intended to make a copy, you can replace this with:

str = [localStr copy];

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:

str = localStr;

If you are trying to only create the string if it has not already been created you could do this:

NSString * str = nil;  ///< Global string.

/// Some class method
-(void) foo:(NSString*) localStr
{
    if(!str)//only create if it is not already created
    {
        str = [[NSString alloc] initWithString:localStr];
    }
}

If you are trying to delete the old string before you assign the new one then it will happen applemagicly when you assign the new string and leave the function scope. There is no need to explicitly "release" the string.

If you do explicitly want to tell the program you don't need the string you can do this:

str = nil;

which will remove str's strong pointer to the string. Unless you are in a situation where you are creating many (or very large) strings within the scope you are usually OK with the above. However, you can look into @autoreleasepool blocks to force the memory to be released.

链接地址: http://www.djcxy.com/p/84278.html

上一篇: 有没有比这更好的替代“开启类型”?

下一篇: 重新分配全局NSString指针