我认为我会谨慎,并通过转换一个类来尝试在现有的Obj-C项目上使用
Swift.还有一个小而简单的.噢亲爱的.
将原始的obj-c音译为Swift应该是直截了当的,所以看起来如此.不幸的是,虽然编码器到持久存储似乎有效,但它在init编码器的第一行出现EXC_BREAKPOINT错误而崩溃.
IF(和大写是有意的)NSCoding / Swift提供与NSCoding / ObjC相同的持久内容,然后我的所有obj-c版本应该能够读取Swift编码的内容,反之亦然.事实证明并非如此 – 当我试图从Swift版本中读取持久性存储时,我完美运行的obj-c版本崩溃了.当然,如果NSCoding正确实现,它应该生成一个可读的东西吗?否则,应该有单独的NSCodingSwift和NSCodingObjC协议?
总而言之,我可以在obj-c中读/写.我不能写/ obj-c和read / swift我可以写/ swift read / obj-c而且我无法在swift中读/写.
以下是两个版本:
let keyBeaconItemNameKey = "name" let keyBeaconItemUUIDKey = "uuid" let keyBeaconItemMajorValueKey = "major" let keyBeaconItemMinorValueKey = "minor" import UIKit import CoreLocation class SMBeaconItem : NSObject,NSCoding { var name : String! var uuid : NSUUID! var major : NSNumber! var minor : NSNumber! init(newName : String,newUUID : NSUUID,newMajor : NSNumber,newMinor : NSNumber ) { name = newName uuid = newUUID major = newMajor minor = newMinor } init( coder decoder : NSCoder!) { name = decoder.decodeObjectForKey(keyBeaconItemNameKey) as String uuid = decoder.decodeObjectForKey(keyBeaconItemUUIDKey) as NSUUID major = decoder.decodeObjectForKey(keyBeaconItemMajorValueKey) as NSNumber minor = decoder.decodeObjectForKey(keyBeaconItemMinorValueKey) as NSNumber } func encodeWithCoder( encoder: NSCoder!) { encoder.encodeObject(name,forKey:keyBeaconItemNameKey) encoder.encodeObject(uuid,forKey:keyBeaconItemUUIDKey) encoder.encodeObject(major,forKey:keyBeaconItemMajorValueKey) encoder.encodeObject(minor,forKey:keyBeaconItemMinorValueKey) } }
工作原创:
@implementation SMBeaconItem - (instancetype)initWithName:(NSString *)name uuid:(NSUUID *)uuid major:(CLBeaconMajorValue)major minor:(CLBeaconMinorValue)minor { self = [super init]; if (!self) { return nil; } _name = name; _uuid = uuid; _majorValue = major; _minorValue = minor; return self; } #pragma mark - Persistence - (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if (!self) { return nil; } _name = [aDecoder decodeObjectForKey:keyBeaconItemNameKey]; _uuid = [aDecoder decodeObjectForKey:keyBeaconItemUUIDKey]; _majorValue = [[aDecoder decodeObjectForKey:keyBeaconItemMajorValueKey] unsignedIntegerValue]; _minorValue = [[aDecoder decodeObjectForKey:keyBeaconItemMinorValueKey] unsignedIntegerValue]; return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.name forKey:keyBeaconItemNameKey]; [aCoder encodeObject:self.uuid forKey:keyBeaconItemUUIDKey]; [aCoder encodeObject:[NSNumber numberWithUnsignedInteger:self.majorValue] forKey:keyBeaconItemMajorValueKey]; [aCoder encodeObject:[NSNumber numberWithUnsignedInteger:self.minorValue] forKey:keyBeaconItemMinorValueKey]; } @end
谢谢你提供的所有帮助.