help-gnustep
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: does NSLog take ownership of the NSString it is given?


From: Richard Frith-Macdonald
Subject: Re: does NSLog take ownership of the NSString it is given?
Date: Sun, 15 Jun 2003 05:19:30 +0100


On Sunday, June 15, 2003, at 12:37  am, Dan Hitt wrote:

I get the impression that NSLog() RELEASEs the NSStrings
it is given.  Is this true?

No.

For example, if i code

  NSString *message=[NSString stringWithFormat:@".... %u",3];
  NSLog(message);
  RELEASE(message);

then i will certainly get a segfault.

That's because *you* are releasing the string you were given
(which you did not own).

But if i either RETAIN the message before handing it to NSLog(),
or refrain from RELEASEing it, then i won't get a segfault.

However, i looked at the code in NSLog.m, and i don't see where this
RELEASEing could be done (e.g., in NSLogv(), for example, the argument
is reassigned in some, but not all, cases).

My understanding from the docs is that an object is created with
a retention count of 1---is this right?---but only deallocated when
the retention count hits 0.

Yes ... there are a few normal ways to create such objects that will be
owned by you ... using +alloc...., +new... or -copy.... and -mutableCopy...
Methods with other names return objects that you don't own.

Thanks in advance for any info, including (especially!) RTFM types,
especially with pointers to chapter and verse on exactly where
RELEASEing occurs.

What is happening here is that you are asking the NSString class
for a temporary string, which is owned by an autorelease pool  ...
that's what makes it temporary.

When the NSAutoreleasePool object which owns the temporary
string is destroyed, the string is also destroyed (unless something
else has retained it).





reply via email to

[Prev in Thread] Current Thread [Next in Thread]