bubibu bubibu - 29 days ago 18
Objective-C Question

Objective c UITableViewCell is not displaying content

The cell in my tableview just won't display any content.

- (void)viewDidLoad {
[super viewDidLoad];
testArray = [[NSMutableArray alloc] init];
}


If the button is clicked, the app will go to next screen and display the table. (The log shows that testString is stored into the testArray)

- (IBAction)goNext:(id)sender {

for(int i=0; i<10; i++){
NSString *testString = @"Hello";
[testArray addObject:testString];
NSLog(@"myArray:\n%@", testArray[i]);
}
UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"test"];
[self presentViewController:vc animated:YES completion:nil];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return testArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *cellId = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];

cell.textLabel.text = testArray[indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", (int)indexPath.row + 1];

return cell;

}


If I do it this way, the content will display.

- (void)viewDidLoad {
[super viewDidLoad];
[self testArraySetup];
}

- (void)testArraySetup{

testArray = [NSMutableArray arrayWithArray:@[@"Pizza",@"Bread",@"Drinks"]];

}


Any advice is much appreciated.

Answer

If you want to pass test Array of one Controller A to another UIViewController B on clicking the Next button you should make the property of testArray in UIViewController B in which you want to show your tableView.

    // UIVIewController A
@interface ViewControllerA ()
{
   NSMutableArray * testArray;
}
    - (void)viewDidLoad {
    [super viewDidLoad];
    testArray = [[NSMutableArray alloc] init];    
    }

        - (IBAction)goNext:(id)sender {

           for(int i=0; i<10; i++){           
                     NSString *testString = @"Hello";
                     [testArray addObject:testString];
                     NSLog(@"myArray:\n%@", testArray[i]);        
                 }
                 UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                 ViewControllerB *vc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"test"];
                 vc.testArray = testArray;
                 [self presentViewController:vc animated:YES completion:nil];

        }

    // ViewController B
    @interface ViewControllerB : UIViewController
        @property (nonatomic,retain)NSMutableArray * testArray;

No need to reinitialise testArray in viewDidLoad of UIViewController B.Otherwise it will reallocate memory to testArray.