无法将对象添加到数组中

时间:2014-12-09 03:16:44

标签: ios objective-c arrays cocoa nsarray

我有以下代码,我收到一个奇怪的错误

 PFQuery *query = [PFQuery queryWithClassName:@"SchoolSpecificData"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        NSMutableArray *data = [[NSMutableArray alloc]init];
        [data addObjectsFromArray:objects];

        NSLog(@"Objects: %d", data.count);

        pickerData = [data valueForKey:@"schoolFullName"];
        NSLog(@"Picker data:%d",pickerData.count);
        NSMutableArray *testarray =[NSMutableArray arrayWithObject:@"Other"];
        [pickerData addObjectsFromArray:testarray];

        NSLog(@"Picker data again:%d",pickerData.count);
        self.SchoolPicker.dataSource = self;
        self.SchoolPicker.delegate = self;
    }];

正如你在前面的块中看到的那样,我将对象添加到一个可变数组中并且工作正常但是由于某种原因它不能使用pickerData数组。此数组是我的类的属性,并定义为NSMutableArray。有关为什么会发生这种情况的任何想法?我也试过添加对象,但它给出了同样的错误。

这是错误:

[2965:202451] -[__NSArrayI addObjectsFromArray:]: unrecognized selector sent to instance 0x7aee6360

2 个答案:

答案 0 :(得分:0)

我认为以下几行是罪魁祸首

 pickerData = [data valueForKey:@"schoolFullName"];

以上是返回不可变数组。

试试这个

 pickerData = [[data valueForKey:@"schoolFullName"]mutableCopy];

<强>更新

建议的重构

PFQuery *query = [PFQuery queryWithClassName:@"SchoolSpecificData"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        pickerData = [NSMutableArray array];
        //TODO: Need validations + capturing strong self inside block is a bad idea:)
        [pickerData addObjectsFromArray:[objects valueForKey:@"schoolFullName"]];
        [pickerData addObject:@"Other"]; 
        //You can set the datasource & delegate outside the block & reload the picker once pickerData is filled. 
        self.SchoolPicker.dataSource = self;
        self.SchoolPicker.delegate = self;
    }];

答案 1 :(得分:0)

我认为应该是

[pickerData addObject:[data valueForKey:@"schoolFullName"]];

而不是

pickerData = [data valueForKey:@"schoolFullName"];