Objective c 什么';这个简单的代码(目标c)有什么错?

Objective c 什么';这个简单的代码(目标c)有什么错?,objective-c,nsurlconnection,Objective C,Nsurlconnection,我想下载一些网页,但这个示例代码似乎不起作用。 它打印“开始下载”,然后退出,为什么不执行委托方法? 示例代码中有什么错误? 谢谢 main.m #进口 #导入“Test.h” int main(int argc,const char*argv[] { @自动释放池{ Test*Test=[[Test alloc]init]; [测试下载数据]; } [NSThread sleepForTimeInterval:21.0f]; 返回0; } 测试h #进口 @接口测试:NSObject @属性(

我想下载一些网页,但这个示例代码似乎不起作用。 它打印“开始下载”,然后退出,为什么不执行委托方法? 示例代码中有什么错误? 谢谢

main.m
#进口
#导入“Test.h”
int main(int argc,const char*argv[]
{
@自动释放池{
Test*Test=[[Test alloc]init];
[测试下载数据];
}
[NSThread sleepForTimeInterval:21.0f];
返回0;
}
测试h
#进口
@接口测试:NSObject
@属性(保留)NSMutableData*接收数据;
@财产(保留)NSURLConnection*连接;
-(void)下载数据;
@结束
Test.m
#导入“Test.h”
@实施测试
-(void)下载数据
{
NSURLRequest*theRequest=
[NSURLRequest requestWithURL:[NSURL URLWithString:@]http://www.sf.net/"]                                  
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
_receivedData=[NSMutableData数据,容量:0];
[NSURLConnection sendSynchronousRequest:请求
回复:无
错误:无];
NSLog(@“开始下载”);
如果(!\u连接){
_接收数据=零;
//通知用户连接失败。
}
}
在这里输入代码
#布拉格标记-
#pragma标记NSURLConnectionDataDelegateenter代码在此处输入方法
-(void)连接:(NSURLConnection*)连接DidReceiverResponse:(NSURResponse*)响应
{
NSLog(@“1”);
[_receivedDatasetLength:0];
}
-(void)连接:(NSURLConnection*)连接didReceiveData:(NSData*)数据
{
NSLog(@“2”);
[_receiveddataappenddata:data];
}
-(无效)连接:(NSURLConnection*)连接
didFailWithError:(n错误*)错误
{
NSLog(@“3”);
_连接=零;
_接收数据=零;
//通知用户
NSLog(@“连接失败!错误-%@%”),
[错误本地化描述],
[[error userInfo]objectForKey:nsurErrorFailingUrlStringErrorKey]);
}
-(无效)连接IDFinishLoading:(NSURLConnection*)连接
{
NSLog(@“4”);
NSLog(@“成功!接收到%lu字节的数据”,(无符号长)[[u receivedData length]);
_连接=零;
_接收数据=零;
}
-(void)ConnectionIDFinishDownloading:(NSURLConnection*)连接目的地URL:(NSURL*)目的地URL
{
NSLog(@“5”);
}
@结束

同步或异步有两种方法:

在同步模式下,未调用任何委托,且右行为

在异步模式下,您需要使用–initWithRequest:delegate:


简而言之,同样的问题是:您的程序需要一个运行循环。您正在使用一个同步请求。不会调用您的委托方法。将请求的结果分配给nsdata对象
nsdata*data=[NSURLConnection sendSynchronousRequest….]或使用异步请求并设置委托!谢谢,我更改了[NSThread sleepForTimeInterval:21.0f];至[[NSRunLoop main runloop]rununteldate:[NSDate dateWithTimeIntervalSinceNow:50.0]];和[NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];to _theConnection=[[NSURLConnection alloc]initWithRequest:theRequest委托:self];再次运行它,它打印begindownload15只有两个方法被调用,数据仍然为null。
main.m

#import <Foundation/Foundation.h>
#import "Test.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        Test * test = [[Test alloc]init];
        [test downloadData];

    }
    [NSThread sleepForTimeInterval:21.0f];

    return 0;
}

Test.h


#import <Foundation/Foundation.h>

@interface Test : NSObject <NSURLConnectionDelegate,NSURLConnectionDataDelegate,NSURLConnectionDownloadDelegate>
@property (retain) NSMutableData * receivedData;
@property (retain) NSURLConnection * theConnection;
- (void) downloadData;
@end

Test.m

#import "Test.h"

@implementation Test
- (void) downloadData
{
    NSURLRequest *theRequest=
      [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.sf.net/"]                                  
                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                   timeoutInterval:60.0];

    _receivedData = [NSMutableData dataWithCapacity: 0];



    [NSURLConnection sendSynchronousRequest:theRequest
                          returningResponse:nil
                                      error:nil];
    NSLog(@"begin download");

    if (!_theConnection) {

        _receivedData = nil;

        // Inform the user that the connection failed.

    }
}

enter code here

#pragma mark -
#pragma mark NSURLConnectionDataDelegateenter code here methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{
    NSLog(@"1");
    [_receivedData setLength:0];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{
    NSLog(@"2");
    [_receivedData appendData:data];

}
- (void)connection:(NSURLConnection *)connection

  didFailWithError:(NSError *)error

{
    NSLog(@"3");
    _theConnection = nil;

    _receivedData = nil;



    // inform the user

    NSLog(@"Connection failed! Error - %@ %@",

          [error localizedDescription],

          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{


    NSLog(@"4");
    NSLog(@"Succeeded! Received %lu bytes of data",(unsigned long)[_receivedData length]);



    _theConnection = nil;

    _receivedData = nil;

}

-(void) connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
{
    NSLog(@"5");
}
@end
_receivedData = [NSURLConnection sendSynchronousRequest:theRequest
                          returningResponse:nil
                                      error:nil];
    NSLog(@"begin download");

    if (!_theConnection) {

        _receivedData = nil;

        // Inform the user that the connection failed.

    }
[NSURLConnection alloc] initWithRequest:delegate:theRequest
                          delegate:self];

NSLog(@"begin download");