I’ve got a single-screen app in which you find two textfields (object and key) and a button (which should store the two Strings in a NSMutableArray. BTW: don’t be confused: “merken” is german for “remember” 😉
my Problem is, that I’d like to fill my NSMutableDictionary this way, but right now it can just save the Object and Key the very first time.
This is my according method:
-(IBAction)merken:(id)sender {
NSString *currentObject = [[NSString alloc] init];NSString *currentKey = [[NSString alloc] init];
currentObject = [typedObject text];
currentKey = [typedKey text];
[dict setValue:currentObject forKey:currentKey];
//Check if the stings have been added to the Dict.
int checkLengh = [dict count];
NSString * checkString = [[NSString alloc] initWithFormat:@"Das Dict hat %d Zeile(n)", checkLengh];
[checkLabel setText:checkString];
[typedObject resignFirstResponder];
[typedKey resignFirstResponder];
}
Any Ideas? I’ve been working on it all day…
The answer is not in the code you have posted; to figure that out where
dictis declared and how it is setup etc. needs to be known; but there are some things which might point to what has gone wrong.First you declare your strings as follows:
This is completely wrong for strings (it is not for all types). An
NSStringis an immutable object and must be given a value when created. However a variable of typeNSString *contains a reference to a string, ornil– for when it is referencing nothing. You only need:To declare the variable which will hold the reference to the
NSStringobject. If you wish you can go a little further an use:So the variable starts with a known value (otherwise local variables will contain a garbage value, instance variables are automatically set to
nil/0/etc. as appropriate). However you will be immediately assigning a value so assigningnilis not needed – there is no chance you’ll accidentally use a garbage value.Getting this wrong suggests you might be unclear about how objects and references work, and you may have made mistakes when declaring and allocating your
NSMutableDictionary.Second you should use
setObject:forKey:to set the key/value:These two methods are subtly different, you usually want
setObject; look at the documentation for the differences.HTH