在进行 JSON 查询时,我无法模拟 MVC 架构。
下面我通过创建一个单独的 NSObject 类来处理查询来异步获取数据。
这就是说,我很困惑我应该在 TableViewController 下面的查询方法中添加什么。
表视图控制器.m
- (void)viewDidLoad
{
[super viewDidLoad];
//refactoring with MVC
self.aQueue = [[[NSOperationQueue alloc] init] autorelease];
self.storeLogos = [NSMutableDictionary dictionary];
[self queryStoreData];
}
-(void)queryStoreData
{
aStoreQuery = [StoreQuery queryForStores:self];
}
-(void)query:(StoreQuery *)query queryResult:(id)object
{
[self.aQueue addOperationWithBlock:^{
//JSONKit?
}
}
StoreQuery.m
@synthesize myConnection, myRequest, storeData;
+(StoreQuery*)queryForStores:(id<StoreQueryDelegate>)aDelegate
{
StoreQuery *storeQuery = [[[StoreQuery alloc] init] autorelease];
storeQuery.delegate = aDelegate;
storeQuery.myRequest = [NSURLRequest requestWithURL:@"URL"];
storeQuery.myConnection = [NSURLConnection connectionWithRequest:storeQuery.myRequest delegate:storeQuery];
storeQuery.storeData = [[NSMutableArray data] retain];
return storeQuery;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.storeData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.storeData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
NSLog(@"Connection Error: %@",[error localizedDescription]);
if (self.delegate) {
[self.delegate request:self didFailWithError:error];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (self.delegate) {
[_delegate request:self didFinishWithObject:self.storeData];
}
}
- (void)dealloc
{
[myRequest release];
[myConnection release];
[storeData release];
[super dealloc];
}