views:

36

answers:

2

Hello everyone,

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

A: 

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

Liam
I add [tableDataList count] to Expressions Window and I receive "out of scope", after that the program received signal: "EXC_BAD_ACCESS"I think the NSMutableArray *array is empty when go out of function. So the tableDataList is empty. Is that right?
haisergeant
It wouldn't be nil, it would point to a garbage location in memory, where the released array used to be.
Kalle
+1  A: 

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.

Kalle
Oh, that's works. Would you please explain me the difference between tableDataList and self.tableDataList? Sorry about this stupid question.Many thanks
haisergeant
The difference is that when you use "self.variable" you are calling the setter for the variable. The setter is a convenience method that you have set up using @property and @synthesize.Since you set it to @property (retain) in your header file, the system will do something like ... (see answer above, I've updated it).
Kalle