2013-10-07 3 views
0

Я разрабатываю приложение iPhone, и хотел бы быть в состоянии создать подобный метод для этого один из Java Андроида:Переопределение функции для экземпляра класса

new GetData(this) { 

     @Override 
     protected void onProgressUpdate(String... string) { 
      ((LoginActivity) context).loginCheck(string[0]); 
     } 
    }.execute(data); 

Здесь я переопределить onProgressUpdate функции для каждого экземпляра чтобы иметь возможность использовать результат с сервера по-другому для каждого экземпляра моего GetData.

В моем объектном коде C У меня есть следующий код:

GetData *myGetData = [GetData alloc]; 
[myGetData initWithValue:@"email=blabla&password=blabla&login=blabla"]; 

Как я могу переопределить некоторые функции для моего экземпляра класса myGetData здесь?

Обычный способ переопределения функций в Obj C, похоже, не работает в этом случае.

Я хотел бы иметь возможность переопределить didReceiveData: (NSData *) данные функции в каждом случае

Это мой GetData класс Сейчас:

@implementation GetData 
-(id) initWithValue: (NSString*) data{ 
self = [super init]; 
// Create the request. 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://myServer.php"]]; 
[request setHTTPMethod:@"POST"]; 
// NSString *content = @"uid=273&facebook=1&getUserNotifications=true"; 
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]]; 

[self print]; 

// Create url connection and fire request 
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
return self; 
} 


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
// A response has been received, this is where we initialize the instance var you created 
// so that we can append data to it in the didReceiveData method 
// Furthermore, this method is called each time there is a redirect so reinitializing it 
// also serves to clear it 
NSLog(@"didReceiveResponse"); 
_responseData = [[NSMutableData alloc] init]; 
//NSLog(@"%@", _responseData); 
} 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
// Append the new data to the instance variable you declared 
NSLog(@"didReceiveData"); 
[_responseData appendData:data]; 
NSString *strData = [[NSString alloc]initWithData:_responseData encoding:NSUTF8StringEncoding]; 
//NSLog(@"%@", strData); 
} 
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection 
       willCacheResponse:(NSCachedURLResponse*)cachedResponse { 
// Return nil to indicate not necessary to store a cached response for this connection 
NSLog(@"connectionwillCacheResponse"); 
return nil; 
} 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
// The request is complete and data has been received 
// You can parse the stuff in your instance variable now 
NSLog(@"connectionDidFinishLoading"); 

} 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
// The request has failed for some reason! 
// Check the error var 
NSLog(@"didFailWithError"); 
} 
@end 
+0

Что вы используете для WebService вызова? NSURLConnection? –

+0

NSURLConnection yeb –

+0

Возможно, вам не составит труда использовать [AFNetworking] (https://github.com/AFNetworking/), его сетевую инфраструктуру, например [volley] (https://android.googlesource.com/platform/frameworks/volley /) в android. –

ответ

1

Рассмотрим этот код:

typedef void (^data_handler_t) (NSURLConnection*connection, NSData*data); 

data_handler_t handler = ^(NSURLConnection*connection, NSData*data){ 
    NSLog(@"%@",data); 
}; 

handler(nil,[NSData new]); 

Затем определите connection:didReceiveData: как

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    handler(connection, data); 
} 

передать блок в конструкторе:

@implementation GetData { 
    data_handler_t _handler; 
} 

-(id) initWithHandler:(data_handler_t) handler { 
    _handler = handler; 
    // ... 
} 

и назвать его как

GetData *getData = [[GetData alloc] initWithHandler:^(NSURLConnection*connection, NSData*data){ 
    NSLog(@"%@",data); 
}]; 
Смежные вопросы