在NSUserDefaults和Realm中保存对象

时间:2018-04-19 16:12:58

标签: ios swift realm nsuserdefaults

是否可以在 NSUserDefaults Realm (Swift)中保存对象?

我发现创建模型时出现问题,因为 NSUserDefaults 需要继承NSObject,而Realm需要继承Object

这样做,引发了这个错误

Multiple inheritance from classes 'Object' and 'NSObject'

1 个答案:

答案 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")!) 继承。