是否可以在 NSUserDefaults 和 Realm (Swift)中保存对象?
我发现创建模型时出现问题,因为 NSUserDefaults 需要继承NSObject
,而Realm需要继承Object
。
这样做,引发了这个错误
Multiple inheritance from classes 'Object' and 'NSObject'
答案 0 :(得分:3)
使用Swift4的import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';
import {Quote} from "../quote.interface";
import {QuoteService} from "../quote.service";
@Component({
selector: 'app-quotes',
templateUrl: './quotes.component.html',
styleUrls: ['./quotes.component.css']
})
export class QuotesComponent implements OnInit {
quotes:Quote[];
loading = false;
busy = false;
constructor(private quoteService:QuoteService) {
}
ngOnInit() {
}
onGetQuotes() {
if (this.busy == false) {
this.loading = true;
this.busy = true;
this.quoteService.getQuotes()
.subscribe(
(quotes:Quote[]) => this.quotes = quotes,
(error:Response) =>console.log(error),
this.loading = false,
this.busy = false
);
}else{
alert('continuous request')
}
}
}
协议,您可以将自定义类保存到Codable
,而无需遵循旧的UserDefaults
协议。
NSCoding
这解决了多重继承的问题,因为你的类型不再需要从class Team: Object, Codable {
@objc dynamic var id:Int = 0
@objc dynamic var name:String = ""
}
let team = Team()
team.id = 1
team.name = "Team"
let encodedTeam = try! JSONEncoder().encode(team)
UserDefaults.standard.set(encodedTeam, forKey: "team")
let decodedTeam = try! JSONDecoder().decode(Team.self, from: UserDefaults.standard.data(forKey: "team")!)
继承。