Pergunta

I have a question :) I often come across the case where I have some objects (books say) and a list of users. Each user has some books. There is also a special case of the currently logged in user who has more attributes than a regular user (posting rights, favorites) etc.

In all previous projects I have been creating a subclass of User called CurrentUser and am adding the current user attributes/logic in there (a regular user can not log out for example). But I always come across the problem of ensuring only one CurrentUser object exists.

How are other people doing this? And am I doing this correctly?

Foi útil?

Solução

I'm not pretty sure I understood your question, but if you want to control that there is only one instance of CurrentUser I will set up a sort of singleton class, say SessionController, that has a property of type CurrentUser.

So, you can access that property anywhere and you know that it's available only one instance of that class and hence only one property for your current user.

CurrentUser* cu = [[SessionController sharedSessionController] currentUser];
if(!cu) // allowed
else // not allowed

When you login (or something else) you populate that property. When you logout, you set it a nil. When you want to enter with another user you can check against that property. This is a simply approach that could work in most cases.

About your question, I'm not pretty sure why you subclassed the User entity. But maybe there is some motivations for it. Make attention when you deal with subclasses. Under the hood, in fact, if you use a sqlite storage, Core Data make flattened the subclass you create. So, in your case you only have a User table which have the attributes you created in CurrentUser.

EDIT

Reading the title of your question, if the control has to be done with the db file, I would create an entity called LoggedUser and avoid using subclass.

Here you can store the id for your the current user and the other properties you want.

Then, if you want to verify if there is one user that is already logged, you could simply set up a request like the following:

NSInteger count = [fetchRequest countForFetchRequest:&error]; // query against `LoggedUser`
if(count >= 1) // not allowed
else // allowed
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top