问问题
407 次
2 回答
1
One possibility is to use an property
in .h
@property (copy, nonatomic) NSArray *locations;
in .m
@synthesize locations;
- (void)viewDidLoad
{
[super viewDidLoad];
self.locations = [NSArray arrayWithObjects:@"New Delhi", @"Durban", @"Islamabad", @"Johannesburg", @"Kathmandu", @"Dhaka", @"Paris", @"Rome", @"Colorado Springs", @"Rio de Janeiro", @"Beijing", @"Canberra", @"Malaga", @"Ottawa", @"Santiago de Chile", nil];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.locations count];
}
于 2012-06-05T21:04:57.200 回答
1
First:
locations = [NSArray arrayWithObjects:@"New Delhi", @"Durban", @"Islamabad", @"Johannesburg", @"Kathmandu", @"Dhaka", @"Paris", @"Rome", @"Colorado Springs", @"Rio de Janeiro", @"Beijing", @"Canberra", @"Malaga", @"Ottawa", @"Santiago de Chile", nil];
[NSArray arrayWithObjects...]
returns an autoreleased object and as you're setting it directly to your instance variable, you need to retain it:
locations = [[NSArray arrayWithObjects:@"New Delhi", @"Durban", @"Islamabad", @"Johannesburg", @"Kathmandu", @"Dhaka", @"Paris", @"Rome", @"Colorado Springs", @"Rio de Janeiro", @"Beijing", @"Canberra", @"Malaga", @"Ottawa", @"Santiago de Chile", nil] retain];
Note:It's a good practice to use properties instead of instance variables.
Second:
cell = [[UITableViewCell alloc] initWithStyle:
UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
According to the memory management rules alloc init returns a retained object, so you'll leak here. Change it to:
cell = [[[UITableViewCell alloc] initWithStyle:
UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
于 2012-06-05T21:08:54.990 回答