Reputation: 19181
I have code that works great for adding a button to the toolbar:
NSArray* toolbarItems = [NSArray arrayWithObjects:flexibleSpace,shuffleBarItem,flexibleSpace,nil];
self.toolbarItems = toolbarItems;
However, I also want to be able to remove toolbar items. When I use the below method, my application crashes:
NSArray* toolbarItems = [NSArray arrayWithObjects:flexibleSpace,nil];
self.toolbarItems = toolbarItems;
Does anyone know how I can dynamically alter the toolbar on the iPhone?
Thanks!
Upvotes: 1
Views: 2331
Reputation: 7422
To remove items from the front or back, you could use subarrayWithRange
, i.e.:
NSRange allExceptLast;
allExceptLast.location = 0;
allExceptLast.length = [self.toolbarItems count] - 1;
self.toolbarItems = [self.toolbarItems subarrayWithRange:allExceptLast];
If you want to remove objects from the middle, you could either use -[NSArray filteredArrayUsingPredicate:]
(which might be overly complicated), or brute force:
NSMutableArray *mutToolbarItems = [NSMutableArray arrayWithArray:self.toolbarItems];
[mutToolbarItems removeObjectAtIndex:<index of object>];
self.toolbarItems = mutToolbarItems;
Note that you shouldn't send removeObjectAtIndex:
to self.toolbarItems
directly (even if you use the above method), since toolbarItems
is exposed as an NSArray
--you'll get a compiler warning, and possibly a crash (since you have no control over whether it will actually be implemented as an NSMutableArray
behind the scenes).
Upvotes: 1
Reputation: 163308
Change it into a NSMutableArray
.
NSMutableArray* _toolbarItems = [NSMutableArray arrayWithCapacity: 3];
[ _toolbarItems addObjects: flexibleSpace,shuffleBarItem,flexibleSpace,nil];
self.toolbarItems = _toolbarItems;
When you want to remove items from the array:
NSInteger indexOfItem = ...
[ _toolbarItems removeObjectAtIndex: indexOfItem ];
self.toolbarItems = _toolbarItems;
Note that in this case you should not use removeObject
since you have repeating objects in your array, and calling [ _toolbarItems removeObject: flexibleSpace ]
will actually remove both instances of flexibleSpace
in the array
Upvotes: 1