haisergeant
haisergeant

Reputation: 1111

Array is empty after function

I am newbie with Cocoa Touch, I have a problem that I try to figure out. I will appreciate if anyone could help.

I would like to create a tableDataList to display on the table. AsyncViewController will call TableHandler fillList method to initialize table data. But after fillList call, the tableDataList return empty.

Can anyone explain me this problem?

In "AsyncViewController.m":

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [self.myHandler fillList];
    [super viewDidLoad];
}

In "TableHandler.m":

@implementation TableHandler

#define ItemNumber 20

@synthesize tableDataList;

- (void) fillList {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:(NSUInteger) 20];

    for (NSUInteger i = 0; i < ItemNumber; i++) {
        [array addObject:[NSString stringWithFormat:@"Row %d", i]];
    }

    tableDataList = [NSArray arrayWithArray:array];
}

Thanks

Upvotes: 1

Views: 199

Answers (2)

Kalle
Kalle

Reputation: 13346

tableDataList needs to retain the new array, or it will be autoreleased soon after your call.

If tableDataList is a @property with retain, just change the line above to:

self.tableDataList = [NSArray arrayWithArray:array];

and the setter will handle it for you.

The equivalent of a @property (retain) NSArray *tableDataList; is in code,

- (void)setTableDataList:(NSArray *)anArray
{
    if (tableDataList != nil) {
        [tableDataList autorelease]; 
    }
    tableDataList = [anArray retain];
}

The above code will automatically release and retain objects when you replace the variable, using self.tableDataList = SOMETHING. However, if you just use tableDataList = SOMETHING you are not using the above setter, you're setting the variable directly.

Upvotes: 1

Liam
Liam

Reputation: 8092

Are you sure it's empty and not nil? You may need to alloc the tableDataList before you use it

Upvotes: 0

Related Questions