3

我有以下2種方法:Objective-C類方法不調用委託方法而實例方法確實

-(void)authenticateUserToGoogle:(NSString *)userName withPassword:(NSString *)password { 


    NSString *URLstr = GOOGLE_CLIENT_LOGIN; 
    URLstr = @"http://www.google.com/ig/api?stock=AAPL"; 
    NSURL *theURL = [NSURL URLWithString:URLstr]; 
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:theURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0]; 

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

    if (!theConnection) { 
     NSLog(@"COuldn't register device information with Parking Server"); 
    } else { 
     NSLog(@"Got a connection!!"); 
     NSMutableData  *_responseData = [NSMutableData data]; 
     NSLog(@"respone_data = %@",_responseData); 

    } 
    } 

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response; 
    NSInteger statusCode = [HTTPResponse statusCode]; 

    if (404 == statusCode || 500 == statusCode) { 
     //[self.controller setTitle:@"Error Getting Parking Spot ....."]; 
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE]; 
     NSLog(@"GOT A 'FUCKED' STATUS CODE"); 

     [connection cancel]; 
     NSLog(@"Server Error - %@", [NSHTTPURLResponse localizedStringForStatusCode:statusCode]); 
    } else if (200 == statusCode) { 
     NSLog(@"GOT A 'OK' RESPONSE CODE"); 

    } 

} 

如果我稱之爲authenticateUserToGoogle方法作爲一個實例方法是這樣的:

[self authenticateUserToGoogle:user withPassword:password] 

我得到以下輸出:

2011-08-12 00:14:08.490 stcoks[81272:f203] Got a connection!! 
2011-08-12 00:14:08.492 stcoks[81272:f203] respone_data = <> 
2011-08-12 00:14:08.726 stcoks[81272:f203] GOT A 'OK' RESPONSE CODE 

但是,如果我改變authenticateUserToGo眄方法是類方法,通過簡單地改變了「 - 」到「+」的方法簽名,然後調用它像這樣:

[MasterViewController authenticateUserToGoogle:user withPassword:password] 

我得到以下輸出:

2011-08-12 00:14:08.490 stcoks[81272:f203] Got a connection!! 
2011-08-12 00:14:08.492 stcoks[81272:f203] respone_data = <> 

在換句話說,它似乎與類方法,委託方法連接didReceiveResponse永遠不會被調用!

任何人都可以向我解釋這種行爲?謝謝!

回答

5

當您使用delegate:self啓動NSURLConnection時,將設置將接收connection:didReceiveResponse:消息的委託對象。如果在類方法中使用self,則此方法也將作爲類方法調用。

2

您正在將委託設置爲自己的方法。如果它是一個類方法,那麼self不包含該類的一個實例。我猜這是要麼是課程本身,要麼是零。

嘗試將兩者都更改爲類方法。

1

除非您還將委託方法更改爲類方法,否則將不會調用它,因爲委託(類)不響應消息 - 只有它的實例纔會響應。

2

如果更改authenticateUserToGoogle方法通過簡單地改變了"-""+"方法簽名是一個類的方法,然後更改connection:didReceiveResponse:委託方法的"-""+"了。所以你的代碼看起來像,

+ (void)authenticateUserToGoogle:(NSString *)userName withPassword:(NSString *)password { 

    // Your code here 
} 

+ (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 

    // Your code here 
}