2011-02-22 18 views
5

NSThread'de bir NSURLConnection kullanıyorum, ancak NSURLConnection'ın temsilci yöntemlerinin hiçbiri yürütülemiyor! NSTread alt sınıfımda ana parçam ve iş parçacığı etkin tutan bir süre döngü var. Herhangi bir yardım?NSThread'de NSUrlConnection - Hiçbir temsil yürütülür!

Bu kodun tamamı için üzgünüm, ancak sorunumu açıklamanın en iyi yolu olduğunu düşünüyorum. Yani bu çoğunlukla bir elma örnek projesinden createConnectionWithPath:userObjectReference

@interface WSDAsyncURLConnection : NSObject 
{ 
    NSMutableData *receivedData; 
    NSDate *connectionTime; 
    NSURLConnection *connection; 

    id _theUserObject; 

} 


@property (nonatomic, retain) NSMutableData *receivedData; 
@property (nonatomic, retain) NSDate *connectionTime; 
@property (nonatomic, assign) NSURLConnection *connection; 

- (void)createConnectionWithPath:(NSString *)thePath userObjectReference:(id)userObject; 


@end 


#import "WSDAsyncURLConnection.h" 

@implementation WSDAsyncURLConnection 
@synthesize connectionTime, receivedData, connection; 


- (void) terminate 
{ 
    if (self.connection) { 
     [self.connection release]; 
     self.connection = nil; 
    } 
} 


- (void) createConnectionWithPath:(NSString *)thePath userObjectReference:(id)userObject; 
{ 
    _theUserObject = userObject; 


    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:thePath] 
               cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60]; 


    self.connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; 

    if (self.connection) 
    { 
     /* record the start time of the connection */ 
     self.connectionTime = [NSDate date]; 

     /* create an object to hold the received data */ 
     self.receivedData = [NSMutableData data]; 
    } 
} 


- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    [self.receivedData setLength:0]; 
} 

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    /* appends the new data to the received data */ 
    [self.receivedData appendData:data]; 
} 

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{  
    [self terminate]; 
} 


- (void) connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    // displays the elapsed time in milliseconds 
    NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:self.connectionTime]; 
    // displayes the length of data received 
    NSUInteger length = [self.receivedData length]; 

    NSString* aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding]; 

    [self terminate]; 


    [[NSNotificationCenter defaultCenter] postNotificationName:WSDAsynchURLConnectionDidFinished 
                 object:_theUserObject 
                 userInfo:[NSDictionary dictionaryWithObject:aStr forKey:@"urlResponseString"]]; 

    NSLog(@"ti=%f, l=%d, response=%@", elapsedTime, length, aStr); 

} 

@end 

Bu kodudur çağıran zaman uyumsuz bağlantısını yapan bir nesnedir ve bir NSThread dışında çalışıyor. Ancak aşağıdaki konu alt sınıfında kullandığımda delege yöntemi yürütülüyor!

@implementation IncomingThread 



- (void) main { 

    NSAutoreleasePool *poool = [[NSAutoreleasePool alloc] init]; 


// I start the URLConnection here ... But no delegate is executed ! 
     [urlConn createConnectionWithPath:@"http://localhost:8888" userObjectReference:nil]; 


    while (![self isCancelled]) { 

     [NSThread sleepForTimeInterval:3.]; 
    } 


    [poool release]; 

} 


- (id) init 
{ 
    self = [super init]; 
    if (self != nil) { 

     urlConn = [[WSDAsyncURLConnection alloc] init]; 
    } 
    return self; 
} 


- (void) dealloc { 

    NSLog(@"deallocating (%@)...", [self className]); 


    [urlConn release]; 

    [super dealloc]; 
} 

cevap

2

Her şeyden önce: ayrı iş parçacığında NSURLConnection kullanmanız gerekmez. Asenkron olduğu için ana parçayı engellemez. sleepForTimeInterval için Dokümanlar

while (![self isCancelled]) { 
     [NSThread sleepForTimeInterval:3.]; 
    } 

:

No run loop processing occurs while the thread is blocked. 
+0

örnek koduna bir göz atacağım Haklısın! Onu özledim! Teşekkür ederim! – Vassilis

+0

xmmm ... 'SleepForTimeInterval' yorumunda bulunmasam bile, hala delege çağrısı yapılmaz. (İş parçacığı bırakmam - ana yöntem sonlandığında, ancak kendi başına serbest bırakılırsa hariç) – Vassilis

+0

Evet, iş parçacığı derhal çıkar. Ayrı bir iş parçacığı kullanmak isterseniz, senkronize isteği kullanın veya ana iş parçacığındaki bir eşzamanlamayı yapın. – Max

1

Bunu zor yoldan yapıyorsunuz. NSURLConnection, iş parçacığına ihtiyaç duyduğu için iş parçacığıyla çok iyi oynamıyor. İş parçanızın bir çalışma döngüsü yok ve bu nedenle kod çalışmıyor. Ana bağlantıdaki bağlantı neden çalıştırılmıyor? Veya bağlantıyı NSOperation, sample code here'da da sarabilirsiniz. Ve şimdi aynı zamanda senkron bir bağlantı kullanma ve bunu global bir GCD kuyruğuna gönderme seçeneğiniz de var.

+0

Çok teşekkür ederim çalışmıyor! NSOperation – Vassilis

0

Hatırlarsanız mı İkincisi: Her zaman bu kod barış parçacığının runloop yürütülmesini durdurmak çünkü bağlantının işlem yoktur temsilci atamak için? gibi

şey: sınıf WSDAsyncURLConnection temsilci yöntemleri uygulayan

self.connection.delegate = self; 

Çünkü bunlar çağrıldığını anlamına gelmez.

+0

Ancak tabiki -> 'self.connection = [[NSURLConnection alloc] initWithRequest: theRequest ** delege: self ** startImmediately: YES];' yukarıdaki kodda. Yine de teşekkürler. – Vassilis

+0

ah evet, sanırım hepsini okumadım :) – Friesgaard

0

Geç ama

Çözüm link diğerleri hayat :) kurtarabilir: NSURLConnection delege yöntemleri

+0

Yanlış bağlantı için özür dilerim, –

+0

http://www.depl0y.com/?p=345 gerçek link –