我有以下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
答案 0 :(得分:1)
我认为这里的问题是在您的dataSource数组中混合NSString
和DrawerItem
。在代码的稍后阶段,您尝试仅将其项目用作字符串,这会引发运行时错误。
解决方案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)
}