been having a little confusion about the retainCount of NSURLConnection

前端 未结 2 557
星月不相逢
星月不相逢 2020-12-11 11:51

first look at these code:

NSURL *url = [[NSURL alloc] initWithString:@\"lasdhfkjasf\"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURL         


        
相关标签:
2条回答
  • 2020-12-11 12:41

    Whilst not technically a duplicate of the question Nikolai linked to, the same thing applies:

    Don't use the retainCount property

    It's possibly the worst thing Apple ever put into NSObject, because it's so nicely named it tricks you into thinking it's actually useful.

    See the question you were previously linked to - Objective C NSString* property retain count oddity - but look for the second answer, the highest rated one.

    0 讨论(0)
  • 2020-12-11 12:56

    Everything is absolutely OK here: NSURLConnection must retain itself to be sure that it can deliver data to the delegate (and to do that it must not be deallocated). If there is no delegate, then nobody listens to that connection and there is no reason to perform anything, so it doesn't retain itself. Connection then releases itself after:

    -(void) connectionDidFinishLoading:(NSURLConnection*) connection
    

    OR

    -(void) connection:(NSURLConnection*) connection didFailWithError:(NSError*) error
    

    From your example:

    . . .
    NSURLConnection *_conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    . . .
    [_conn release];
    

    if retainCount was 1, then after [_conn release] the object would be deallocated immediately and there would be no loading at all.

    To all of you, who says that retainCount works incorrectly: you just don't know how it works. As for NSString 'oddity': this is not oddity, this is just performance optimization. 2147483647 retain count means that object is constant in memory (and is deleted when app terminates). This is done when the value is known during compilation:

    NSString* str = @"12345"; //has 2147483647 retain count.
    
    0 讨论(0)
提交回复
热议问题