Pergunta

I'm watching the lesson of standford CS193P, in particular the lecture n°7. I have some doubts about NSUserDefaults. This is the part of code :

#define FAVORITES_KEY @"CalculatorGraphViewController.Favorites"

- (IBAction)addToFavorites:(id)sender
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *favorites = [[defaults objectForKey:FAVORITES_KEY] mutableCopy];
    if (!favorites) favorites = [NSMutableArray array];
    [favorites addObject:self.calculatorProgram];
    [defaults setObject:favorites forKey:FAVORITES_KEY];
    [defaults synchronize];
}

I read the documentation about NSUserDefaults, but I don't understand this code in particular [[defaults objectForKey:FAVORITES_KEY] mutableCopy]. FAVORITES_KEY is @"CalculatorGraphViewController.Favorites".

My question is why I should should use CalculatorGraphViewController.Favorites? I don't understand the dot! It seems to me that a structure of getter or setter but Favorites have a capital letter and then CalculatorGraphViewController.Favorites doesn't make sense.

Can You help me please?

Foi útil?

Solução

You can think of it as a NSDictionary, and the key you provide is only for your own reference. It is for you to retrieve the value back later. You can call it a string like @"CalculatorGraphViewController.Favorites" or any other string that you like. They name it this way just to identify that this is the value for Favorites choices recorded in CalculatorGraphViewController, I believe.

Outras dicas

As others have noted, the key is an arbitrary string. The catch is that there can be many parts of your app writing into the defaults. If you picked something really simple as the key, say “favourites”, it could very well happen that two parts of your app would both attempt to use the same key for something different. (Say, for favourite artists and favourite songs.)

This is a common problem in programming, and it’s usually solved by introducing a namespace, or some kind of prefix that makes the clashes less probable. You can often see namespaces in Java classes, something like com.someguy.AppName.SomeClassName. Or even in domain names – like developer.facebook.com and developer.apple.com. Both use the term “developer”, but both differ in the namespace (com.facebook versus com.apple).

You can use the same solution in your use case and introduce a namespace into your defaults key. A logical choice for the namespace is the class name, because you are unlikely to have two classes with the same name. Thus you arrive at the CalculatorGraphViewController prefix. The dot is just a customary way to separate the components in the namespace.

It is just key, it can be any string or object, but not nil

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top