nsmutablearray insertobject atindex:0无效

时间:2012-11-29 04:08:46

标签: nsmutablearray uibarbuttonitem

有人可以帮我理解为什么insertobject atindex:0行无法向nsmutablearray添加任何内容吗?感谢。

- (void)setSplitViewBarButtonItem:(UIBarButtonItem *)splitViewBarButtonItem
{
    if (_splitViewBarButtonItem != splitViewBarButtonItem) {
        NSMutableArray *toolbarItems = [self.toolbar.items mutableCopy];
        if (_splitViewBarButtonItem) [toolbarItems removeObject:_splitViewBarButtonItem];
        if (splitViewBarButtonItem) {
            [toolbarItems insertObject:splitViewBarButtonItem atIndex:0];
            NSLog(@"setSplitViewBarButtonItem: toolbarItems has %u objects",toolbarItems.count);
        }
        self.toolbar.items = toolbarItems;
        _splitViewBarButtonItem = splitViewBarButtonItem;
    }
}

工具栏是先前在同一.m文件中定义的私有属性

@property (nonatomic, weak) UIToolbar *toolbar;

我也试过更换线

NSMutableArray *toolbarItems = [self.toolbar.items mutableCopy];

NSMutableArray *toolbarItems = [[NSMutableArray alloc]init];
toolbarItems = [self.toolbar.items mutableCopy];

但仍未向toolbarItems添加任何内容。调试器始终将splitViewBarButtonItem显示为非null,并且我的NSLog保持打印为零。

非常感谢。

2 个答案:

答案 0 :(得分:0)

我设法通过用此替换if(_splitViewBarButton)...行来获取insertObject行

if (_splitViewBarButtonItem) {
    toolbarItems = [self.toolbar.items mutableCopy];
    [toolbarItems removeObject:_splitViewBarButtonItem];
} else {
    toolbarItems = [[NSMutableArray alloc]init];
}

换句话说,如果设置了_splitViewBarButtonItem(有一个条形按钮),则将其删除。否则,需要分配init。

我现在的问题是作业

self.toolbar.items = toolbarItems;

无效,条形按钮现在显示在详细信息视图中。有什么建议吗?

答案 1 :(得分:0)

确实,我真正需要的是让我的工具栏属性为IBOutlet,即更改

@property (nonatomic, weak) UIToolbar *toolbar;

@property (nonatomic, weak) IBOutlet UIToolbar *toolbar;

通过此更改,我最初发布的代码按原样运行。我认为当未定义为IBOutlet时,工具栏未正确实例化。