If I have a piece of code that looks like this:
- (void)testSomething
{
__weak NSString *str = [[NSString alloc] initWithFormat:@"%@", [NSDate date]];
NSLog(@"%@", str);
}
the output will be (null) because there are no strong references to str and it will be immediately released after I allocate it. This makes sense and is spelled out in the Transitioning to ARC guide.
If my code looks like this:
- (void)testSomething
{
__weak NSString *str = [NSString stringWithFormat:@"%@", [NSDate date]];
NSLog(@"%@", str);
}
then it correctly prints out the current date. Obviously you would expect it to work in a non-ARC world, since str
would be autoreleased and therefore valid until this method exits. However, in ARC-enabled code people generally consider the two forms (stringWithFormat
& alloc/initWithFormat
) to be equivalent.
So my question is whether code like the second example is guaranteed to work under ARC. That is, if I have a weak reference to an object that I get via what we would normally consider an autoreleasing convenience constructor, is it guaranteed to be safe to use that reference in the same scope I normally would have without ARC (i.e. until the method exits)?
See Question&Answers more detail:os