I am working on Objective-C application. There I have this snippet:
QString result;
NSString *tmp = nil;
tmp = [activeApp bundleIdentifier];
result = QString::fromNSString(tmp);
NSLog(@"activeApplicationBundleId 2");
if (tmp) {
NSLog(@"dealloc");
//[tmp dealloc]; // <--- this causes crash
}
else {
NSLog(@"do not dealloc");
}
return result;
I don't understand why it crashes. I have checked documentation from Apple and bundleIdentifier is property defined with copy
@property(readonly, copy) NSString *bundleIdentifier;
I also have read that I should be responsible of deallocating string. Why is this crashing? If I use instead:
NSRunningApplication* activeApp = [[NSWorkspace sharedWorkspace] frontmostApplication];
return QString::fromNSString([activeApp bundleIdentifier]);
Would I have memory leak for not deallocating the NSString ?
Just in case QString::fromNSString
QString QString::fromNSString(const NSString *string)
Constructs a new QString containing a copy of the string NSString.
Thanks in advance
First, all of this is irrelevant and shouldn't be there if you're under ARC. So let's assume you are not using ARC, and do manual memory management:
by convention, you're not owning the NSString returned by bundleIdentifier
, so you should not attempt to release it*
even if you were owning the string, you're supposed to release it with a call to release
, not dealloc
. release
will decrement the retain counter, and only call dealloc
if the retain counter becomes zero. As a rule of thumb, you never call dealloc directly; doing so may free an object that is still referenced from somewhere else, resulting in memory corruption and a hard crash
*) The copy
attribute of the property definition is misleading; it's describing what happens when a new value is assigned to the property. Since the property is publicly declared as readonly
, this reveals an implementation detail, which should not be in the public definition in the header (it would better be in a private interface extension not publicly visible). Feel free to file a bug report with Apple which will never get any attention.