5

假设我使用JSONXML API 从使用异步 NSURLConnection 的 URL 获取有关我的项目的数据,将其解析为NSMutableArray,然后填充NSTableView

我有一个模型:项目 我有一个控制器:TableViewController(充当表数据源和委托)

我应该将启动请求并将结果解析为NSMutableArray的代码放在哪里。

我应该有:

1:

Project 中的一个方法调用-(NSMutableArray* ) getAllProjects并从我的 Controller 调用它。

或 2:

我是否应该枚举Project*对象的NSMutableArray,例如在我的控制器中调用ProjectsArray* ;每次打电话?[[Project alloc] init]

选项 1 对我来说更有意义,因为我可能想从多个控制器中获取所有项目,这样可以节省重复代码,我只需要在我的项目模型中调用公共方法。在这种情况下,我会做很多[[self alloc] init]陈述吗?这个可以吗?我的模型也需要是一个NSURLConnection委托。它是否正确?

4

3 回答 3

2

毫无疑问,它必须在您的模型中。

原因 :

因为您将需要从不同的控制器多次更新它,所以您将来可以使用 KVO。

于 2012-11-06T14:31:22.940 回答
1

根据我的经验,我认为好的方法是在模型(ProjectsArray)中使用解析例程,在另一个类中使用连接内容,它会启动连接并返回原始 NSData(例如通过委托),然后将其传递给模型解析它。这样您的模型或视图控制器将不会有多个角色。

至于[[Project alloc] init]每次需要数据时调用 - 您可以在模型类中使用静态引用,然后通过类似的方式获取它- (ProjectsArray *)instance

于 2012-11-06T16:39:13.487 回答
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
于 2013-03-01T04:14:34.020 回答