【发布时间】:2015-05-04 02:08:13
【问题描述】:
我正在开发一个带有自定义类的 Swift 项目。该项目的旧 Objective-C 版本有一个自定义的 init 方法,如下所示。
自定义类的自定义初始化
-(id) initWithURLDictionary: (NSDictionary *) dictionary{
self = [super init];
if (self) {
self.URLDictionary = dictionary;
}
return self;
}
使用此类时,我将使用自定义初始化程序创建对象,然后将自定义类的委托设置为 self。
// Create a temporary dictionary of the feeds, allocate and initialize the FLODataHandler object and set the delegate (me) to self.
NSDictionary *URLTempDictionary = [[NSDictionary alloc] initWithObjectsAndKeys: kFLOCyclingURL, @"FLO Cycling", kTriathleteURL, @"Triathlete", kVeloNewsURL, @"Velo News", kCyclingNewsURL, @"Cycling News", kRoadBikeActionURL, @"Road Bike Action", kIronmanURL, @"Ironman", nil];
self.dataHandler = [[FLODataHandler alloc] initWithURLDictionary: URLTempDictionary];
self.dataHandler.delegate = self;
在 Swift 中我有点困惑。看来我有两个选择。选项 1 会让我在自定义类中创建一个自定义初始化程序。
自定义类中的自定义初始化器
init(dictionary : [String:String]) { self.URLDictionary = dictionary }
过程与Objective-C相同。
let URLTempDictionary = [kFLOCyclingURL : "FLO Cycling", kTriathleteURL : "Triathlete", kVeloNewsURL : "Velo News", kCyclingNewsURL : "Cycling News", kRoadBikeActionURL : "Road Bike Action", kIronmanURL : "Ironman"]
var tempDataHandler = FLODataHandler(dictionary: URLTempDictionary)
self.dataHandler! = tempDataHandler
选项 2 没有通过投诉,但似乎不完整。
我不会创建自定义初始化程序,而是简单地执行以下操作。自定义类有一个名为 URLDictionary 的字典属性。
let URLTempDictionary = [kFLOCyclingURL : "FLO Cycling", kTriathleteURL : "Triathlete", kVeloNewsURL : "Velo News", kCyclingNewsURL : "Cycling News", kRoadBikeActionURL : "Road Bike Action", kIronmanURL : "Ironman"]
self.dataHandler!.URLDictionary = URLTempDictionary
self.dataHandler.delegate = self
所以我的问题与自定义初始化程序的需要和使用
有关var tempDataHandler = FLODataHandler(dictionary: URLTempDictionary)
是否使用
self.dataHandler!.URLDictionary = URLTempDictionary
实现同样的结果?
保重,
乔恩
【问题讨论】:
-
您能告诉我您是如何在班级中声明 dataHandler 成员的吗?
标签: objective-c swift