title: TableviewCells are not inserted as expected
body: <p>I have a reusableTablViewCell that will be simply echoed to the tableview whenever a user gives an input in the textbook and clicks send button, my problem is that the cells are not behaving as expected few times the cells are inserted correctly and few times they won't.</p>
  
  <p>Expected Behaviour: when the user clicks send button after he has finished typing some text in the text box the same value should be printed twice (like sending and receiving the same text).</p>
  
  <pre><code>//view somewhat looks like this on expected behaviour
  
           '''''''''
           '  hi   '
           '''''''''
  '''''''''
  '  hi   '
  '''''''''
  
  </code></pre>
  
  <p>Current Behaviour: Sometimes it does give me the expected behaviour, but some times both the cells are on the same side </p>
  
  <p>EX:</p>
  
  <pre><code>//view when it doesn't work as expected
  
            ''''''' 
            ' hi  '
            '''''''
  
            '''''''
            ' hi  '
            '''''''
  
  or something like 
  
  ''''''''
  '  hi  '
  ''''''''
  
  ''''''''
  '  hi  '
  ''''''''
  </code></pre>
  
  <p><strong>And sometimes when we scroll, the cells change their position(being odd Cell and Even-cell which u can see in the code) from sender to receiver and vice-versa.</strong></p>
  
  <p>My code </p>
  
  <pre><code>//FirstTableViewController.h
  
  
  #import &lt;UIKit/UIKit.h&gt;
  @class SecondViewController;
  @interface FirstTableViewController : UITableViewController
  @property (strong, nonatomic) IBOutlet UITableView *messageView;
  @property (nonatomic,readwrite) NSInteger counter;
  @property (nonatomic,readwrite) NSMutableArray *userInput;
  @property (nonatomic,readwrite) NSMutableDictionary *heightAtIndexPath;
  @property (nonatomic, assign) BOOL shouldScrollToLastRow;
  + (id)sharedInstance;
  @end
  @interface ChatMessageCellTableViewCell : UITableViewCell
  @property (nonatomic, retain) UILabel *formLabel;
  @property (nonatomic, retain) UIView *bubbleBackView;
  @end
  
  </code></pre>
  
  <pre><code>//FirstTableViewController.m
  
  #import "FirstTableViewController.h"
  BOOL isReceived;
  @interface ChatMessageCellTableViewCell (){
      NSLayoutConstraint *leadingConstraint;
      NSLayoutConstraint *trailingConstraint;
  }
  @end
  
  @implementation ChatMessageCellTableViewCell
  -(void) loaded{
      if(isReceived){
          [self.bubbleBackView setBackgroundColor:[UIColor whiteColor]];
          [self.formLabel setTextColor:[UIColor blackColor]];
  
      }
      else{
          [[self bubbleBackView] setBackgroundColor:[UIColor colorWithRed:(66/255) green:(137/255.0)  blue:1  alpha:1.0]];
          [self.formLabel setTextColor:[UIColor whiteColor]];
      }
  }
  -(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
      [self setBackgroundColor:[UIColor clearColor]];
      self.formLabel = [UILabel new];
      self.bubbleBackView = [UIView new];
  
      //[self.bubbleBackView setBackgroundColor:[UIColor yellowColor]];
      [self.bubbleBackView.layer setCornerRadius:12];
      self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
      if(self){
          [[self contentView] addSubview:self.bubbleBackView
           ];
          [self loaded];
          [self.bubbleBackView setTranslatesAutoresizingMaskIntoConstraints:NO];
          [[self contentView] addSubview:self.formLabel];
  
          [self.formLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
          if (@available(iOS 9.0, *)) {
              [self.formLabel.topAnchor constraintEqualToAnchor:self.topAnchor constant:32].active=YES;
              [self.formLabel.bottomAnchor constraintEqualToAnchor:self.bottomAnchor constant:-32].active=YES;
              [self.formLabel.widthAnchor constraintLessThanOrEqualToConstant:250].active=YES;
  
              [self.bubbleBackView.topAnchor constraintEqualToAnchor:_formLabel.topAnchor constant:-16].active=YES;
              [self.bubbleBackView.bottomAnchor constraintEqualToAnchor:_formLabel.bottomAnchor constant:16].active=YES;
              [self.bubbleBackView.trailingAnchor constraintEqualToAnchor:_formLabel.trailingAnchor constant:16].active=YES;
              [self.bubbleBackView.leadingAnchor constraintEqualToAnchor:_formLabel.leadingAnchor constant:-16].active=YES;
              leadingConstraint= [self.formLabel.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:32];
              trailingConstraint = [self.formLabel.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-32];
              if(isReceived){
                  [leadingConstraint setActive:YES];
                  [trailingConstraint setActive:NO];
              }
              else{
                  [leadingConstraint setActive:NO];
                  [trailingConstraint setActive:YES];
              }
          } else {
              // Fallback on earlier versions
          }
          [self.formLabel setLineBreakMode:NSLineBreakByWordWrapping];
          [self.formLabel setNumberOfLines:0];
          [self.formLabel sizeToFit];
          [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-40-[bodyLabel]-40-|" options:0
                                                                                   metrics:nil
                                                                                     views:@{ @"bodyLabel":self.formLabel}]];
  
      }
      return self;
  }
  @end
  @interface FirstTableViewController ()
  {
      NSArray *messages;
      FirstTableViewController *classA;
  }
  @end
  
  @implementation FirstTableViewController
  +(id)sharedInstance
  {
      static FirstTableViewController *sharedClassA = nil;
      static dispatch_once_t onceToken;
      dispatch_once(&amp;onceToken, ^{
          sharedClassA = [[self alloc] init];
      });
      return sharedClassA;
  }
  - (void)viewDidLoad {
      [super viewDidLoad];
       self.heightAtIndexPath = [NSMutableDictionary new];
      self.userInput = [[NSMutableArray alloc] init];
      [self.tableView registerClass:[ChatMessageCellTableViewCell class] forCellReuseIdentifier:@"id"];
      [[self tableView] setSeparatorStyle:UITableViewCellSeparatorStyleNone];
      [self.tableView setBackgroundColor:[UIColor colorWithWhite:0.95 alpha:1]];
      [[self navigationController] setTitle:@"Meetings"];
       classA = [FirstTableViewController sharedInstance];
      [classA setCounter:(classA.userInput.count)];
      [classA setMessageView:(self.messageView)];
  }
  
  - (void)didReceiveMemoryWarning {
      [super didReceiveMemoryWarning];
  }
  
  
  - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
      return 1;
  }
  
  - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
      classA.counter=classA.userInput.count;
      return classA.counter;
  }
  
  
  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      NSString *cellIdentifier = (indexPath.row % 2 == 0 ? @"EvenCell" : @"OddCell"); //just to differentiate the sending and receiving cell.
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
      ChatMessageCellTableViewCell *messageCell = (ChatMessageCellTableViewCell*) cell;
      if (messageCell == nil) {
          messageCell = [[ChatMessageCellTableViewCell alloc] initWithStyle: UITableViewCellStyleDefault
              reuseIdentifier:cellIdentifier];
      }
      if(indexPath.row % 2 == 0) // simple logic to differentiate and apply my constraints to the sending and receiving cells.
      {
          isReceived =TRUE;
      }
      else{
          isReceived = FALSE;
      }
      [[messageCell formLabel]setText:classA.userInput[indexPath.row]];
      [messageCell setSelectionStyle:UITableViewCellSelectionStyleNone];
      [[self tableView] setEstimatedRowHeight:50.0];
      [self.tableView setRowHeight:UITableViewAutomaticDimension];
      return messageCell;
  }
  
  -(void)viewWillLayoutSubviews{
      if(classA.shouldScrollToLastRow){
          [classA setShouldScrollToLastRow:NO];
          dispatch_async(dispatch_get_main_queue(),^{
              NSIndexPath *path = [NSIndexPath indexPathForRow:(self-&gt;classA.counter)-1 inSection:0];
              //Basically maintain your logic to get the indexpath
              [self-&gt;classA.messageView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:NO];
          });
      }
  
  }
  
  -(void)viewDidAppear:(BOOL)animated{
      [super viewDidAppear:animated];
  
  }
  -(void)dealloc{
      NSLog(@"Dealloc!!!");
  }
  @end
  
  </code></pre>
  
  <pre><code>//SecondViewController.m
  
  //sendButtonClicked is the function from where the data is passed to the FirstViewController's tableview cell.
  -(IBAction)sendButtonClicked{
      NSString *input = self.ChatTextInput.text;
      if([input isEqualToString:@""]){
          NSLog(@"this is a nil ");
      }
      else{
          [inputValues addObject:input];
          [inputValues addObject:input];
          [classA setUserInput:inputValues];
          [classA setCounter:inputValues.count];
          [self.ChatTextInput setText:nil];
          [classA setShouldScrollToLastRow:YES];
          [classA.messageView reloadData];
      }
  }
  </code></pre>
  
  <p>This is basically a chat view which I'm actually trying to achieve everything is good except this abnormal behaviour.</p>
  
  <p>I hope anyone can take some time and correct me where am I wrong.</p>
  
  <p>UPDATE: Any one who is looking for basic chatView in objective-C can use the code above as an reference, use the code above and correct the mentioned things in the accepted answer.</p>