Search code examples
objective-cswiftnsarrayblock

Passing an NSArray from Swift into Objective-C function


I am calling a function from an Objective-C class. I passing an array from my Swift class into an Objective-C function.

Here is my code for the Swift

var videosAutoCompletion:[String] = []

completeSearch.autocompleteSegesstions(searchText, self.tableView, self.videosAutoCompletion)

Objective-C Function

 -(void)autocompleteSegesstions : (NSString *)searchWish :(UITableView*)table :(NSArray*)stringArray

Inside the Objective-C function i had a block

  dispatch_sync(dispatch_get_main_queue(), ^{
        self.ParsingArray = [[NSMutableArray alloc]init]; //array that contains the objects.
        for (int i=0; i != [jsonObject count]; i++) {
            for (int j=0; j != 1; j++) {
                //NSLog(@"%@", [[jsonObject objectAtIndex:i] objectAtIndex:j]);
                [self.ParsingArray addObject:[[jsonObject objectAtIndex:i] objectAtIndex:j]];
                //Parse the JSON here...
                //NSLog(@"Parsing Array - %@",self.ParsingArray);

                stringArray =  [self.ParsingArray copy];
                [table reloadData];

            }
    }

    });

I am getting this error for the following line.

Variable is not assignable (missing __block type specifier) at line

 stringArray =  [self.ParsingArray copy];

Solution

  • You are trying to modify the value of the stringArray function parameter within a block, so you should tell that to the compiler. You could try making a copy right before the dispatch_sync call as such:

        __block NSArray *stringArrayCopy = [stringArray copy];
    

    and use the copy within the block.

    This will silence the compiler errors, but please note that if your intention is to change your Swift videosAutoCompletion array by setting the stringArray parameter within the ObjC method, you need to change your approach. Setting stringArray = [self.ParsingArray copy]; only has an effect local to the autocompleteSegesstions::: function.