Lifetime of weak local variables with ARC

前端 未结 2 944
一个人的身影
一个人的身影 2020-12-18 06:45

If I have a piece of code that looks like this:

- (void)testSomething
{
  __weak NSString *str = [[NSString alloc] initWithFormat:@\"%@\", [NSDate date]];
           


        
2条回答
  •  不思量自难忘°
    2020-12-18 07:41

    The conventions of autoreleasing and allocing still apply in the world of ARC. The only difference is that ARC will insert extra retain/release calls to make it much harder to leak objects or access a dealloced object.

    In this code:

    __weak NSString *str = [[NSString alloc] initWithFormat:@"%@", [NSDate date]];
    

    The only place the object is retained (or equivalent) is the alloc. ARC will automatically insert a release command, causing it to be immediately dealloced.

    Meanwhile, in this code:

     __weak NSString *str = [NSString stringWithFormat:@"%@", [NSDate date]];
    

    By convention, the return value of a convenience constructor like this must be an autoreleased object*. That means the current autoreleasepool has retained the object and will not release it until the pool is drained. You are therefore all but guaranteed that this object will exist for at least the duration of your method - although you probably shouldn't rely on this behaviour.

    (* or retained in some other way)

提交回复
热议问题