假设我使用 JSON 或 XML API,使用异步NSURLConnection从URL获取有关我的项目的数据,并将其解析为 NSMutableArray < / strong>然后填充 NSTableView 。
我有一个模型:项目 我有一个控制器: TableViewController (充当表数据源和委托)
我应该在哪里放置启动请求的代码并将结果解析为 NSMutableArray 。
我应该:
1:
Project内部的一个名为-(NSMutableArray* ) getAllProjects
的方法,并从我的Controller中调用它。
或2:
我应该枚举 Project * 对象的 NSMutableArray ,在我的控制器中调用实例 ProjectsArray * ;每次拨打[[Project alloc] init]
?
选项1对我来说更有意义,因为我可能希望从多个控制器获取所有项目,这将节省重复代码,我只需要在我的Project模型中调用公共方法。在这种情况下,我会做很多[[self alloc] init]
语句吗?这个可以吗?我的模型也需要是 NSURLConnection 委托。这是对的吗?
答案 0 :(得分:2)
毫无疑问,它必须在您的模型中。
原因:
因为您需要从不同的控制器多次更新它,所以将来可以使用KVO。
答案 1 :(得分:1)
根据我的经验,我认为最好的方法是在模型中使用解析例程(ProjectsArray)和另一个类中的连接东西,它启动连接并返回原始NSData(例如通过委托),你通过到模型来解析它。这样你的模型或viewController将没有多个角色。
至于每次需要数据时调用[[Project alloc] init]
- 您可以在模型类中使用静态引用,然后通过- (ProjectsArray *)instance
答案 2 :(得分:0)
/*
* UITableViewController has the word "controller" in it but that
* does not make it a controller... it's a view. Pure and simple.
*
* /This/ is a controller...
*/
@implementation MyController
@synthesize data; // assume readonly @property in interface
-(void)fetchData {
NSURLConnection *connection;
// Set up URL connection, etc. Speaking very loosely, and
// lossing over some important threading details...
NSURLResponse *response = GetResponse();
NSError *__autoreleasing error;
@autoreleasepool {
// build objects. premature optimization is the root of all evil,
// but if you're really worried about too much allocation, you
// can resist duplication with custom logic in parse().
self.data = parse([response data], &error);
}
if (data == nil) {
// Error notification
}
else { // Success notification
NSNotification *didFetch = [NSNotification notificationWithName:@"didFetch" object:self.data userInfo:nil];
[[NSNotificationCenter defaultCenter] performSelectorOnMainThread:@selector(postNotification:) withObject:didFetch waitUntilDone:NO];
}
}
@end
@interface MyTableViewController ()
@property (unsafe_unretained) MyController *controller;
@property (strong, nonatomic) NSArray *dataView;
@end
@implementation MyTableViewController
@synthesize controller = _controller;
@synthesize dataView = _dataView;
-(void)viewDidLoad {
_controller = [MyController controller]; // singleton
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(updateData:)
name:@"didFetch"
object:nil];
}
-(IBAction)buttonPress {
[_controller fetchData]; // again, I'm glossing over threading details...
}
-(void)updateData {
// Controller owns the data, we just get a view of it here.
self.dataView = [[_controller data] arrayOfSomeSort];
[self.view reloadData];
}
@end