将用户定义的对象添加到NSMutableArray

时间:2016-03-17 19:00:48

标签: ios objective-c swift unrecognized-selector

我有以下swift类,想要在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];

并给我以下例外

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

2 个答案:

答案 0 :(得分:1)

我认为这里的问题是在您的dataSource数组中混合NSStringDrawerItem。在代码的稍后阶段,您尝试仅将其项目用作字符串,这会引发运行时错误。

解决方案nr。 1 在swift var dataSource: [DrawerItem] = []中声明数组这会抛出编译错误

解决方案nr。 2 使用objective-c轻量级泛型@property (nonatomic, strong) NSMutableArray<DrawerItem*> *dataSource;,如果存在不匹配,将生成编译器警告

答案 1 :(得分:-1)

你可以这样做

    import Foundation

    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
        }
    }

    //creating the first obj
    var drawer: DrawerItem = DrawerItem()

    drawer.tag = "Tag Test"
    drawer.title = "Title Test"

    //creating the second obj
    var drawer1: DrawerItem = DrawerItem()

    drawer1.tag = "Tag Test 1"
    drawer1.title = "Title Test 1"

    var drawerArray:[DrawerItem] = [DrawerItem]()

    //adding to the drawerArray
    drawerArray.append(drawer)
    drawerArray.append(drawer1)


    //testing the array
    for x in drawerArray{
        print(x.title)
    }