-1

in aViewController.h

#import <UIKit/UIKit.h>

@interface aViewController : UIViewController
@property (nonatomic) NSMutableArray *pageImages;
@end

in bViewController.m

#import "aViewController.h"

// ...

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;

    aViewController *testViewController = [[aViewController alloc] init];
    [testViewController.pageImages addObject:@"lalala yeyeye"];

    NSLog(@"%@", testViewController.pageImages); // Error?

    [self.navigationController pushViewController:testViewController animated:YES];
}

The NSLog in bViewController.m outputs:

2013-10-08 18:23:38.398 quo.mk.e[56804:1ca03] (null)

What did I do wrong here? Why did the NSMutableArray remain empty although I had added an object into it?

Update: both UIViewController objects are made programmatically. I am using the passing data forward tips mentioned here to populate the array, but I'm stumped on why it won't work.

Community
  • 1
  • 1
hfz
  • 317
  • 2
  • 15

1 Answers1

5

When you allocate aViewController it won't allocate the objects inside that class.

You need to allocate them also, means you need to allocate memory for the NSMutableArray else it will be nil.

You should do like:

aViewController *testViewController = [[aViewController alloc] init];
testViewController.pageImages = [[NSMutableArray alloc] init];
[testViewController.pageImages addObject:@"lalala yeyeye"];
NSLog(@"%@", testViewController.pageImages);
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
  • This works. Just wanted to add that I initially thought having `pageImages` as a `@property` means it gets initialized automatically. I guess not. – hfz Oct 08 '13 at 11:36
  • @hfz: no, it won't be initialized. You need to initialize each member object. Or you can override the `- (id)init` in the `aViewController` and allocate each member object there – Midhun MP Oct 08 '13 at 12:08