Search code examples
objective-cunrecognized-selectornsimageview

Unrecognized selector with array objects.


The NSImageView objects once in the array become strings. How to I convert them into NSImageView to avoid unrecognized selector error generated by the last line?

NSArray *array = [NSArray arrayWithObjects: @"chip1”, @"chip2” nil],
for (id image in array) {
[image setImage: nil];
}

Solution

  • The @"..." notation in Objective-C is shorthand for creating an NSString. In the above code example, you're creating an array of NSString's, which is why you're getting the unrecognized selector error when you call setImage:.

    Assuming chip1 and chip2 are instances of NSImageView, you should be doing the following:

    NSArray *array = [NSArray arrayWithObjects:chip1, chip2, nil];
    

    You can avoid issues like this in future, by using Objective-C Generics when defining your array:

    NSArray <NSImageView*>*array = [NSArray arrayWithObjects:chip1, chip2, nil];
    

    This would give a compiler error if you tried to add a class other that NSImageView to the array.