在我的-viewDidLoad
方法中,我初始化了 many NSMutableDictionaries
,并将它们添加到类头文件中NSMutableArray
声明的初始化 via中。@property
相关代码如下所示。简而言之,我正在从 HTML 网页中抓取信息。
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
_regionalDicts = [[NSMutableArray alloc] init];
for (int i = 0; i < [strings count]; i++) {
NSString *str = [strings objectAtIndex:i];
//Property parser:
if ([str rangeOfString:@"<td>"].location != NSNotFound) {
NSString *parsedTD1 = [str stringByReplacingOccurrencesOfString:@"<td>" withString:@""];
NSString *parsedTD2 = [parsedTD1 stringByReplacingOccurrencesOfString:@"</td>" withString:@""];
NSString *parsedTD3 = [parsedTD2 stringByReplacingOccurrencesOfString:@" " withString:@"\n"];
NSString *final = [parsedTD3 stringByReplacingOccurrencesOfString:@"\t" withString:@""];
//NSLog(@"Final string: %@", final);
if ([final isEqualToString:@""]) {
continue;
}
if (gotEventType == NO) {
gotEventType = YES;
[dict setObject:final forKey:@"type"];
continue;
}
if (gotRegional == YES && gotLocation == NO) {
gotLocation = YES;
[dict setObject:final forKey:@"location"];
continue;
}
if (gotLocation == YES && gotCity == NO) {
gotCity = YES;
NSString *cityToReturn = [final stringByReplacingOccurrencesOfString:@"\n" withString:@""];
[dict setObject:cityToReturn forKey:@"city"];
continue;
}
if (gotRegional == YES && gotEventType == YES && gotCity == YES && gotLocation == YES && gotURL == YES) {
gotRegional = NO;
gotEventType = NO;
gotCity = NO;
gotLocation = NO;
gotURL = NO;
NSLog(@"Regional: %@", [dict objectForKey:@"regional"]);
NSLog(@"Type: %@", [dict objectForKey:@"type"]);
NSLog(@"City: %@", [dict objectForKey:@"city"]);
//Testing to see if anything is nil
NSLog(@"Location: %@\n", [dict objectForKey:@"location"]);
if (!_regionalDicts) {
NSLog(@"Dict is nil");
}
[_regionalDicts addObject:dict];
NSLog(@"Objects in array: %u", [_regionalDicts count]);
NSMutableDictionary *tempDict = [_regionalDicts objectAtIndex:[_regionalDicts count]-1];
NSLog(@"Regional in array: %@", [tempDict objectForKey:@"regional"]);
[dict removeAllObjects];
continue;
}
很明显,生成的字典是在可变数组中生成并保留的,_regionalDicts
可变数组在头文件中声明如下:
@property (strong, nonatomic) IBOutlet NSMutableArray *regionalDicts;
但是,当我尝试将信息传递给同一类中的表格视图单元格时,字典的内容为空。数组中的对象与我期望的字典一样多,但它们不包含任何内容。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (_regionalDicts) {
NSMutableDictionary *dict = [_regionalDicts objectAtIndex:0];
NSLog(@"Setting label %@", [dict objectForKey:@"city"]);
[cell.textLabel setText:[dict objectForKey:@"regional"]];
}
return cell;
}
回报:
2013-04-01 19:58:50.250 MatchScrape[53570:207] Setting label (null)
我只能想象应该归咎于内存管理问题。为什么在添加它们的方法范围之外访问时,类数组的内容会被取消,但允许数组保留相同的计数?