NSMutableDictionary not Setting Keys - iphone

All,
I'm sure I'm overlooking something, but I've been staring at this code for too long trying to figure out what's going on.
-(IBAction)continue:(id)sender
{
//setters for the limits
NSLog(#"Log ageUnder18: %#", ageUnder18.text); //returns Y
NSMutableDictionary *cardLimits;
[cardLimits setObject:ageUnder18.text forKey:#"ageUnder18"];
NSLog(#"Just set %#", [cardLimits objectForKey:#"ageUnder18"]); //returns NULL
//more code here
}
Why is that returning NULL?
Thanks in advance,
James

You're not initializing your variable. In fact, you're rather lucky that you aren't crashing outright on the -setObject:forKey: line. Your cardLimits variable currently holds garbage memory, i.e. whatever was on the stack at the address that the variable occupies. You need to use
NSMutableDictionary *cardLimits = [NSMutableDictionary dictionary];
Note that the Static Analyzer should be able to catch this for you.

You are not allocating cardLimits at any time. You need:
NSMutableDictionary *cardLimits = [[NSMutableDictionary alloc] init];

You aren't initializing a NSMutableDictionary.

Related

iOS NSMutabledictionary is null when I setValue and forKey

I know I may been doing something very stupid but I can not figure out where is the error on this code:
NSString *string=#"some string";
[self.dataResponse setValue:string forKey:#"Code"];
Also I tried:
NSString *string=#"some string";
[self.dataResponse setObject:string forKey:#"Code"];
but in both cases my nsmutable dictionary self.dataResponse is null. Any of you knows what I'm doing wrong?
I really appreciate your help.
You need to Alloc and Init the NSMutableArray to set values in it. Example:
self.dataResponse = [[NSMutableArray alloc] init]; // This is alloc and init
NSString *string = #"Some Val";
[self.dataResponse setValue:string forKey:#"Code"];
your variable self.dataResponse is just nil.
You have to say
self.dataResponse = [NSMutableDictionary new];
to allocate and instantiate a dictionary.
afterwards you can assign values to the keys!
I think you must not have initialised your mutable dictionary yet, wether using alloc/init or a convenience initialiser. Until you do that, setting any object for key will do nothing. You can do this lazily or in view did load (amongst other places).

NSDictionary Memory leaks

I implement a method to return a dictionary in my app. But I find a memory leak using instrument, I tried to figure it out, but I still cannot find it. Can anyone help me out?
Thanks in advance, here is the code for that methods:
-(NSMutableDictionary *)initDict
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:self.name forKey:#"Name"];
//Some similar set object for key here...
return dict;
}
I think the problem is from allocing memory for dict and not releasing it. But in the method, it seems I cannot release dict. So is there any method to fix the leak?
All variants are good. Here is third variant (choose wisely):
Replace
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
with
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
I think you just need to change the last line of initDict to this:
return [dict autorelease];
When you are creating any object in your function and you want to return them then you should always create it in a way that those objects are autoreleased. So you should change your code like below.
NSMutableDictionary *dict = [[[NSMutableDictionary alloc]init]autorelease];
So whenever you create any object just call autorelease method on that.

Adding string to an array

i wanted to know how to add strings into an array.
I used the following methods but it is showing null.
1) [arrData addObject:[NSString stringWithString:strlast]];
2) [arrData addObject:strlast];
Thanks in advance
You can't add anything to an NSArray once it's created. You need to use an NSMutableArray if you want to make changes to it.
Update: You may actually have two problems.
Using an NSArray instead of an NSMutableArray when mutability is needed.
Not initializing the array object (either kind). If arrData is nil, you can happily send as many messages as you want to nil. Nothing will happen.
If it is showing null (nil) you need to make sure you set arrData somewhere in your code before trying to addObject:.
arrData = [[NSMutableArray alloc] init];
Also strlast is a string so use your second example, the first example is pointless.
[arrData addObject:strlast];
Did you allocate an array and assign it to arrData?
Try:
NSMutableArray *arrData = [NSMutableArray array];
NSString *string = #"My string";
[arrData addObject:string];
NSLog(#"%#", [arrData objectAtIndex:0]); //logs "My string"
If you're using a non-mutable array, you can also use arrayByAddingObject:
arrData = [arrData arrayByAddingObject: strlast];
but a mutable array is probably a better idea.

Refresh Value in NSMutableDictionary using ViewWillAppear

See this code:
int i = years;
NSLog(#"Years i: %i",i);
NSString *syears= [NSString stringWithFormat:#"%d",i];
menuList = [[NSMutableArray alloc] init];
[menuList addObject:[NSMutableDictionary
dictionaryWithObjectsAndKeys:
#"years", kLeftKey,
syears, kRightKey, nil, kControllerKey, nil]];
The above is an extract from ViewWillAppear. When I switch between tabs ViewWillAppear is doing it's job and the data is updating down as far as NSString *syears= [NSString stringWithFormat:#"%d",i]; but after that my array doesn't get updated with the latest value of syears. I tried using setObject and setValue but these don't work with NSMutableArray. Any ideas?
Keys and values in NSDictionary need to be non-nil NSObjects. So you've definitely got an issue with a nil in there, and there may be a question about kLeftKey et al, for which you haven't shown the definitions.
More generally, it would help to know what you are doing with menuList and what you mean by "my array doesn't get updated". Are you trying to display it? Using it as a data source somewhere? You are creating the array anew here -- could a previous reference be being left around and displayed?

Why am I having trouble with a deep copy in Objective C?

I'm assuming my understanding of how to perform a deep copy isn't just there yet. The same with some sub-optimal memory handling that I'm performing down below. This code below probably depicts a shallow copy, and I believe that's where my problem might be. I have some cookie-cutter code for an example that looks like the following:
NSArray *user = [[xmlParser createArrayWithDictionaries:dataAsXML
withXPath:kUserXPath] retain];
if([user count] > 0) {
self.name = [[user valueForKey:#"name"] copy];
}
// Crash happens if I leave the next line un-commented.
// But then we have a memory leak.
[user release];
[xmlParser release];
Unfortunately when I comment out [user release], the code works, but we have an obvious memory leak. The method createArrayWithDictionaries:withXPath: was refactored last night when the SO community helped me understand better memory management. Here's what it looks like:
- (NSArray *)createArrayWithDictionaries:(NSString *)xmlDocument
withXPath:(NSString *)XPathStr {
NSError *theError = nil;
NSMutableArray *dictionaries = [NSMutableArray array];
CXMLDocument *theXMLDocument = [CXMLDocument alloc];
theXMLDocument = [theXMLDocument initWithXMLString:xmlDocument
options:0
error:&theError];
NSArray *nodes = [theXMLDocument nodesForXPath:XPathStr error:&theError];
for (CXMLElement *xmlElement in nodes) {
NSArray *attributes = [xmlElement attributes];
NSMutableDictionary *attributeDictionary;
attributeDictionary = [NSMutableDictionary dictionary];
for (CXMLNode *attribute in attributes) {
[attributeDictionary setObject:[attribute stringValue]
forKey:[attribute name]];
}
[dictionaries addObject:attributeDictionary];
}
[theXMLDocument release];
return dictionaries;
}
I'm guessing there's a couple of issues that might be going on here:
Auto release on my dictionaries array is happening, thus my app crashing.
I'm not performing a deep copy, only a shallow copy. Thus when the user array is released, self.name is done for.
With NSZombieEnabled, I see the following:
*** -[CFString respondsToSelector:]:
message sent to deallocated instance 0x1ae9a0
Also, the final call where the backtrace shows this is crashing contains the following code in a separate module from the other two methods:
User *u = self.user;
NSString *uri = [NSString stringWithFormat:#"%#/user/%#/%#",
[self groupName], u.userId, kLocationsUri];
Between all the auto releasing/copies/retain happening between the client code and createArrayWithDictionaries:withXPath, I'm a bit confused as to the real problem here. Thanks again for helping me understand.
OK, you don't need to retain the return value from createArrayWithDictionaries: since you're not keeping it around. The return value is autoreleased. I'd strongly recommend reading up on how autoreleasing works. You only retain things that you intend to keep around in your object.
Also, user is an NSArray. If you call [user valueForKey:#"name"], you'll get another NSArray of values representing the values of the name key for each of the objects in users. Furthermore, how is the name property on your object defined? If you declared it as copy or retain (I believe retain is the default if you don't specify it yourself), you don't need to copy or retain the value. Indeed, the accessor should always be responsible for doing the memory management, not the caller. If you wrote your own accessor (i.e. you didn't use the #synthesize keyword), you need to make sure you do the memory management there.
I'm guessing what you meant to write was something more like this:
NSArray *user = [xmlParser createArrayWithDictionaries:dataAsXML withXPath:kUserXPath];
if ([user count] > 0)
self.name = [[user objectAtIndex:0] objectForKey:#"name"];
[xmlParser release];
I think your troubles are stemming from a misunderstanding of how memory management works in Objective-C.
Hope this helps.
Auto release on my dictionaries array is happening, thus my app crashing.
If the caller intends to keep the array around somewhere, it needs to retain it. Otherwise, it will crash when it tries to access the (now-deceased) object.
If the caller is going to store it in a property, it must use the self.dictionaries = […] syntax, not dictionaries = […]. The former is a property access, which calls the setter method; the latter is a direct instance variable assignment.
Coming back to your actual question, that of a deep copy: You need to get the sub-elements of every element and put them in each element's dictionary.
Basically, you need a recursive method (or a queue, but that's harder—file under premature optimization until you've proven you need it) that takes an element and returns a dictionary, and then you need to call this method on each of your element's child elements, and collect the results into an array and put that into the dictionary you're creating.
I would recommend making this recursive method an instance method of the element. Something like:
- (NSDictionary *) dictionaryRepresentation {
NSMutableDictionary *attributeDictionary = [NSMutableDictionary dictionary];
for (CXMLNode *attribute in attributes) {
[attributeDictionary setObject:[attribute stringValue] forKey:[attribute name]];
}
NSArray *childElements = [self childElements];
return [NSDictionary dictionaryWithObjectsAndKeys:
attributeDictionary, #"attributes",
[childElements valueForKey:#"dictionaryRepresentation"], #"childElements",
nil];
}
Then you replace the loop in createArrayWithDictionaries:withXPath: with a similar valueForKey: message. I'll leave you to fill it in.
valueForKey: is Key-Value Coding's principal method. In both places, we're making use of NSArray's handy implementation of it.
(If the use of valueForKey: still doesn't make sense to you, you should read the KVC Programming Guide. KVC is vitally important in modern Cocoa, so you do need to read this sooner or later.)