IPhone - 从数组设置NSString,双重标准!

时间:2009-09-27 01:24:09

标签: iphone objective-c cocoa-touch

在下面的代码中,我使用来自NSMutableArray'categage'的值设置表视图单元格文本,这是我的视图控制器的属性。这很好。

但是当我在另一个方法中尝试完全相同的代码时,它会崩溃(它编译时没有错误或警告)。如果我在didSelectRowAtIndexPath方法中更改以下行:

NSString *categoryName = [categories objectAtIndex:indexPath.row];

NSString *categoryName = [[NSString alloc] initWithString:@"test"];

它有效...任何想法?

// Customize the appearance of table view cells.
- (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] autorelease];
    }

 // Configure the cell.
 NSString *categoryName = [categories objectAtIndex:indexPath.row];
 cell.textLabel.text = categoryName;

    return cell;
}




// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    printf("User selected row %d\n", [indexPath row] + 1);

 ButtonsPageViewController *bView =  [ButtonsPageViewController alloc];
 NSLog(@"created instance of buttonspageviewcontroller");

 NSString *categoryName = [categories objectAtIndex:indexPath.row];
 NSLog(@"category name set");

 bView.selectedCategory = categoryName;
 NSLog(@"selected category property set");

 [self.navigationController pushViewController:bView animated:YES];
 NSLog(@"push view controller");

 [bView release];
}

2 个答案:

答案 0 :(得分:2)

之间的区别
NSString *categoryName = [categories objectAtIndex:indexPath.row];

NSString *categoryName = [[NSString alloc] initWithString:@"test"];

第一行是复制指向对象的指针(保留计数不会改变),而第二行是创建一个新对象(保留计数= 1)。

cellForRowAtIndexPath中,当您设置text属性时,它会复制或保留字符串,所以您没问题。在didSelectRowAtIndexPath中,您设置的属性为ButtonsPageViewController,我假设它是您自己的代码,但可能不是复制或保留对象。

此外,该行

ButtonsPageViewController *bView =  [ButtonsPageViewController alloc];

会导致问题。您需要调用init来正确初始化对象。你在那一行所做的就是为它分配内存。

一般来说,看起来你需要了解Retain / Release内存管理。这应该可以省去一些麻烦。

答案 1 :(得分:1)

就像苯扎多说的那样,selectedCategory中保留ButtonsPageViewController值是一个问题。

您使用的是@property@synthesize,还是您正在编写自己的访问者?如果是前者,您可能需要查看属性声明属性。否则,它可能是您的自定义访问器中的保留/释放事件。

Declared PropertiesThe Objective-C 2.0 Programming Laungauge部分是声明合成访问器规则的良好资源。

相关问题