0

Within my storyboard I have a simple view controller that contains a UITableView within it.

enter image description here

SceneFormVC.m

@property (nonatomic, strong) IBOutlet SceneFormTV  *sceneFormTable;

In the process of improving my MVC and making a 'lighter' VC, I subclassed the UITableView for better seperation of concerns and code reuse.

SceneFormTV.h

@interface SceneFormTV : UITableView <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

SceneFormTV.m

@implementation SceneFormTV

- (id)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self)
    {
         self.dataSource = self;
         self.delegate   = self;
    }

    return self;
}

The issue here is when I try to set the dataSource/delegate = self inside my subclass during initWithCoder (as called by the storyboard setup), then it has no effect in causing the rest of the UITableView methods to be called (eg. (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath)

But if I set the dataSource/delegate pointers within the main VC (SceneFormVC.m), then the UITableView works as expected.

@implementation SceneFormVC

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.sceneFormTable.dataSource = self.sceneFormTable;
    self.sceneFormTable.delegate   = self.sceneFormTable;

I don't quite understand why my SceneFormTV subclass fails to operate when it sets up itself with the exact same dataSource/delegate pointers internally?

Sebastian Dwornik
  • 2,526
  • 2
  • 34
  • 57
  • 2
    I'm not sure why that doesn't work, but making the table it's own data source is not good MVC design. The table (the V in MVC) shouldn't know anything about the model, whereas the data source obviously does. If you want to make a lighter view controller, you can create a separate class (NSObject subclass) to be the data source. – rdelmar Jul 30 '14 at 05:28
  • I mostly likely will still separate out the datasource components further. But for now want it further away from the VC file to promote modularity and reuse for other VC's. FYI: I'm building a forms engine using UITableView's. – Sebastian Dwornik Jul 30 '14 at 06:01

1 Answers1

1

This one originally targets IBOutlets but should be valid in your case too.

The objects do not yet exist when initWithCoder is called, and they do when viewDidLoad is called. Check your initWithCoder method by logging out the value of worldView using something like:

NSLog(@"%@", self.datasource);

and it will be nil. They will be initialized before the call to viewDidLoad, so you can set a them there.

Source: Objective-C iOS Development Using viewDidLoad or initWithCoder when setting Variables and Why?

Community
  • 1
  • 1
Akaino
  • 1,025
  • 6
  • 23