2013-07-30 45 views
0

我是ios的初學者。這是AFNetworking的簡單代碼示例。如何從塊內獲取對象並將其用於其他類或方法?

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://yourServerAddress.com/"]]; 
[httpClient setParameterEncoding:AFFormURLParameterEncoding]; 
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" 
                 path:@"http://yourServerAddress.com/example?name=foo" 
                parameters:nil]; 
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]]; 
    AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request 
             success:^(AFHTTPRequestOperation *operation, id responseObject) { 


              NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]); 
             } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
              //-- This block gets invoked when the operation fails 
              NSLog(@"Error: %@", error.localizedDescription); 
             }]; 

的responseObject將被打印到控制檯,但我的問題是:如何獲得responseObject並在另一個類或方法使用它呢?

編輯1:

我試圖用一種方法:

- (void)responseFromBlock:(id)response { 

NSLog(@"responseObject from the block : %@",response); 

}

而且我使用它的塊中:

[self responseFromBlock:responseObject]; 

但答案是:

response object from the block : <7b226572 726f7222 3a7b2263 6f646522 3a313230 307d2c22 72657375 6c74223a 5b7b2263 6964223a 22313234 222c2263 6e616d65 223a2244 69766174 227d2c7b 22636964... 
+1

你守在開始編程iOS應用程序之前,ld學習面向對象編程。 「Objective C 2.0編程」對於初學者來說是一本好書。這個問題很簡單! –

回答

0

這可能是這樣的:

@interface YourClassDealingWithAFNetworking 

@property (nonatomic, retain) id object; 

@end 

然後塊內:

self.object = responseObject; 

現在你得到它,你需要的地方

只是不」可以使用它t忘記釋放它在dealloc:

self.object = nil; 
+0

我正在使用ARC。它不工作,但沒有ARC我認爲它的工作原理... – makvalti

+0

即使在弧下也能工作 –

相關問題