3

我有以下两种方法:

-(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

但是,如果我将 authenticateUserToGoogle 方法更改为类方法,只需将方法签名中的“-”更改为“+”,然后像这样调用它:

[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 永远不会被调用!

谁能向我解释这种行为?谢谢!

4

4 回答 4

5

当您使用 NSURLConnection 启动时,它会设置将接收消息delegate:self的委托对象。connection:didReceiveResponse:如果self在类方法中使用,该方法也将作为类方法调用。

于 2011-08-12T04:26:57.293 回答
2

您在方法中将委托设置为 self 。如果它是类方法,则 self 不包含该类的实例。我猜它要么是班级本身,要么是零。

尝试将两者都更改为类方法。

于 2011-08-12T04:26:20.877 回答
2

如果您authenticateUserToGoogle通过简单地将方法签名中的"-"to更改为类方法,则将委托方法的to也更改为。所以你的代码看起来像,"+"connection:didReceiveResponse:"-""+"

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

    // Your code here
}

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

    // Your code here
}
于 2011-08-12T04:48:55.387 回答
1

除非您还将委托方法更改为类方法,否则不会调用它,因为委托(类)不响应消息——只有它的实例会。

于 2011-08-12T04:26:58.977 回答