ios - 如何为 API 凭据设置/取消设置多个帐户

标签 ios iphone swift oop core-data

我有一个应用可以保存多个用户帐户,以便从我的 API 检索数据。始终有一个帐户设置为事件或标记为 TRUE。当我选择一个不同的帐户时,我会停用以前激活的帐户并激活所选帐户或将其设置为 TRUE。我在我的帐户 TableView 中使用 CoreData 来执行这些操作。

当我的应用程序启动时,我的 API 类会检查我的 CoreData 以查看哪个帐户处于事件状态,并将其凭据分配给我的 Credential 对象。 然后我使用这些凭据访问我的服务器并从中获取数据。到目前为止,一切都很完美。

我的问题是,当我选择不同的帐户并在我的 didSelectRowAtIndexPath 方法中重置我的 Credentials 对象时,我的 API 类仍然具有以前事件帐户的凭据。我可以看到/打印 Credentials 对象具有所选帐户的凭据。

如何调整我的对象以仅拥有/使用选定帐户的凭据?

class API {
    var credentials:Credentials!
    init(){
        self.credentials = getActiveStore()
        // I use self.credentials.username to make API calls later in the code
    }


 func getActiveStore() -> Credentials?{
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!
    let fetchRequest = NSFetchRequest(entityName: "User")
    fetchRequest.returnsObjectsAsFaults = false
    fetchRequest.predicate = NSPredicate(format: "active = %@", 1 as NSNumber) 
    var error:NSError?

    let fetchResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as! [User]
    if fetchResults.count == 1 {
        let name = fetchResults[0].name
        let url = fetchResults[0].url
        let username = fetchResults[0].username
        let password = fetchResults[0].password
        return Credentials(name: name, url: url, username: username, password: password)
    }
    return nil
}

}

现在这是永远不会改变的类。当我在选择不同的账户后刷新我的数据时,我看到的数据属于以前活跃的账户。 API 类不想更改。

最佳答案

您是否在每次选择新单元格时都创建新凭据?因为您的凭据仅在对象的 criation 中得到更新

init(){
    self.credentials = getActiveStore()
    // I use self.credentials.username to make API calls later in the code
}

如果您想要更新凭据,则必须创建一个新的 API 实例。

另一种方法是创建一个更新方法并在选择新单元格时调用它

func updateCredentials(){
    self.credentials = getActiveStore()
    // I use self.credentials.username to make API calls later in the code
}

关于ios - 如何为 API 凭据设置/取消设置多个帐户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30520524/

相关文章:

iphone - 旋转固定位置的 UILabel

iphone - 由于未捕获的异常而终止应用程序 'NSUnknownKeyException'

iphone - 从堆栈加载 UIViewController

iphone - 复制只读 NSMutableArray 的正确方法

ios - Swift 如何在 AnyObject 数组中查找对象

ios - 在 ViewController.swift 和 segue 中分配给 UIButton 的属性适用于模拟器,但不适用于设备

ios - 使用AVAudioRecorder在后台录制语音

ios - AVAudioSessionManager availableInputs "Unknown selected data source for port iPhone Microphone"

ios - 180x180 图标真的是必需的吗?

ios - UIStatusBarStyle 不适用于 Swift