Set UITableView Delegate and DataSource

后端 未结 5 1519
生来不讨喜
生来不讨喜 2020-12-06 01:29

This is my problem: I have this small UITableView in my storyboard:\"enter

<
相关标签:
5条回答
  • 2020-12-06 01:46

    Presumably you're using ARC? Your myTableDelegate is only referenced in a local variable in viewDidLoad -- once that method ends, it's deallocated. (In the delegate/datasource pattern, objects do not own their delegates, so the table view's references back to your object are weak.) I wouldn't expect that alone to cause a crash, but it's likely key to your problem.

    0 讨论(0)
  • 2020-12-06 01:52

    The delegate of an UITableView object must adopt the UITableViewDelegate protocol. Optional methods of the protocol allow the delegate to manage selections, configure section headings and footers, help to delete methods.

    enter image description here

    0 讨论(0)
  • 2020-12-06 01:55

    rickster is right. But I guess you need to use a strong qualifier for your property since at the end of your viewDidLoad method the object will be deallocated anyway.

    @property (strong,nonatomic) SmallTable *delegate;
    
    // inside viewDidload
    
    [super viewDidLoad];
    self.delegate = [[SmallTable alloc] init];    
    [self.myTable setDelegate:myTableDelegate];
    [self.myTable setDataSource:myTableDelegate];
    

    But is there any reason to use a separated object (data source and delegate) for your table? Why don't you set SmallViewController as both the source and the delegate for your table?

    In addition you are not creating the cell in the correct way. These lines do nothing:

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    cell.textLabel.text = @"Hello there!";
    

    dequeueReusableCellWithIdentifier simply retrieves from the table "cache" a cell that has already created and that can be reused (this to avoid memory consumption) but you haven't created any.

    Where are you doing alloc-init? Do this instead:

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(!cell) {
        cell = // alloc-init here
    }
    // Configure the cell...
    cell.textLabel.text = @"Hello there!";
    

    Furthermore say to numberOfSectionsInTableView to return 1 instead of 0:

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        // Return the number of sections.
        return 1;
    }
    
    0 讨论(0)
  • 2020-12-06 01:57

    setDelegate will not retain the delegate.

    And

    numberOfSectionsInTableView method has to return 1 instead of 0;

    0 讨论(0)
  • 2020-12-06 01:58
    (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        // Return the number of sections.
        return 0;
    }
    

    Number of sections should be set at least one

    0 讨论(0)
提交回复
热议问题