问题
I used this example to create a segmented view. In my viewDidLoad
method I am getting a warning and code crashes.
- (void)viewDidLoad {
[super viewDidLoad];
self.segmentedViewControllers = [self segmentedViewControllerContent];
NSArray * segmentTitles = [self.segmentedViewControllers arrayByPerformingSelector:@selector(title)];
self.segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentTitles];
self.segmentedControl.selectedSegmentIndex = 0;
self.segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
[self.segmentedControl addTarget:self
action:@selector(didChangeSegmentControl:)
forControlEvents:UIControlEventValueChanged];
self.navigationItem.titleView = self.segmentedControl;
[self.segmentedControl release];
[self didChangeSegmentControl:self.segmentedControl];
}
I am getting a warning in this line:
NSArray * segmentTitles = [self.segmentedViewControllers arrayByPerformingSelector:@selector(title)];
that NSArray may not respond to arrayByPerformingSelector.
回答1:
arrayByPerformingSelector:
is not a valid message to be sent to NSArray
. This method is probably in one of the category extensions of NSArray
that the original code uses. Check the original example you are following and try to find where arrayByPerformingSelector:
is defined, then #import
that file in your code.
回答2:
arrayByPerformingSelector:
is a connivence method someone has written to avoid doing this:
NSMutableArray * tempArray = [NSMutableArray array];
for (id thing in things)
{
[tempArray addObject:thing.name];
}
NSArray * namesOfthings = [tempArray copy];
However, there is already something in the iOS stack that will do this for free!
NSArray * namesOfthings = [things valueForKeyPath:@"unionOfObjects.name"];
You can read more about KVC collection operations in NSHipsters blog post. For an obscure API it's actually really useful. I am sad it took me this long to find it.
来源:https://stackoverflow.com/questions/8377395/nsarray-issue-in-segmentedcontrol