The str1
is null, because you only have weak reference to the string, so ARC may deallocate it immediately because you have no strong references to it. In fact, compiler may even warn you of this:
warning: assigning retained object to weak variable; object will be released after assignment.
The str2
is Hello
because stringWithFormat
creates and "autorelease" object (an object with no strong references, but that is not deallocated until the pool is drained, i.e. after you yield back to the OS). It's not "owned by the framework", but merely hasn't be deallocated yet.
Note, looking at memory management with NSString
can sometimes be problematic (especially when dealing with string literals) because there are internal optimizations that sometimes affect its memory management, but these results you show us are precisely what you'd expect.
Given the atypical NSString
memory management, you may want to observe this pattern using your own, custom object:
@interface CustomObject: NSObject
+ (instancetype)customObject;
@end
@implementation CustomObject
+ (instancetype)customObject {
return [[self alloc] init];
}
@end
And
__weak CustomObject *obj1 = [[CustomObject alloc] init];
__weak CustomObject *obj2 = [CustomObject customObject];
NSLog(@"obj1=%@; obj2=%@", obj1, obj2);
You will see that obj1
will consistently be nil
in this case, but obj2
is not. The basic rule of memory management is that you own any object whose names start with “alloc”, “new”, “copy”, or “mutableCopy”. Thus, these objects have ownership transferred to you and ARC will release them for you (i.e. you only have one weak
reference, so it's immediately released). Objects whose names start with anything besides those prefixes, have not passed ownership to you (and thus, in Objective-C, have been passed to your app as autorelease objects that will be deallocated if there are no strong references when the pool is drained.
To the root of your question, whether the object is "owned by the framework", the answer is generally no, but there are exceptions. For example NSString
has some optimizations that keeps string references around. Likewise there are UIImage
methods, notably imageNamed
that cache images. Etc.
But, generally, you shouldn't worry about what the OS is doing. Just make sure you resolve your own strong references and let the OS do what it will do. Generally, if it does caching, these caches are purged upon memory pressure, anyway.
"Hello"
for all strings. – Avi