NSArray issue in segmentedcontrol

落爺英雄遲暮 提交于 2019-12-11 16:36:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!