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 
}