Search code examples
iosobjective-cswiftunrecognized-selector

add user defined object to NSMutableArray


I have the following swift class and want to add it in NSMutableArray

   class DrawerItem : NSObject{

    var tag : String = ""
    var title : String = ""

    override init () {

        self.tag = "";
        self.title = "";
    }

    init(tag: String) {

        self.tag = tag
    }

    init(title: String) {

        self.title = title
    }
}



self.dataSource = [NSMutableArray new];
[self.dataSource addObject:@"hello"]; //it works 

DrawerItem *item = [DrawerItem new]; // not working
item.tag = @"test";
item.title = @"test";

[self.dataSource addObject:item];

and give me the following exception

uncaught exception 'NSInvalidArgumentException', reason: '-[Khawater.DrawerItem isEqualToString:]: unrecognized selector sent to instance 

Solution

  • I think the problem here is mixing NSString and DrawerItem in your dataSource array. At a later point in your code you try to use its items only as Strings and this throws the runtime error.

    Solution nr. 1 declare the array in swift var dataSource: [DrawerItem] = [] This will throw a compilation error

    Solution nr. 2 Use objective-c lightweight generics @property (nonatomic, strong) NSMutableArray<DrawerItem*> *dataSource; which will generate compiler warning if there is a mismatch