App crashing when trying to setValue in NSMuableDictionary - ios

My app is crashing when I try to set value in NSMutableDictionary.
Here is the code below which demostrate the crash, I am not able to find out any crash log also in the console.
NSArray *b =[[a objectAtIndex:1] valueForKey:#"value"];
NSMutableDictionary *b1 =[b objectAtIndex:0];
NSString *str = self.tes;
[b1 setValue:str forKey:#"value"];
Please help me regarding this.
b1 Dictionary log
{
question = "vale";
type = a;
}

setValue:forKey: is part of the NSKeyValueCoding protocol, which among other things, lets you access object properties from the likes of Interface Builder. setValue:forKey: is implemented in classes other than NSDictionary.
setObject:forKey: is NSMutableDictionary's reason to exist. Its signature happens to be quite similar to setValue:forKey:, but is more generic (e.g. any key type).
So in your case just replace all setValue:forKey with setObject:forKey and valueForKey: with objectForKey:
--
Difference between objectForKey and valueForKey?

So you said you are getting EXC_BAD_ACCESS crash. Try turning on Zombies in Xcode’s Scheme editor. See Enable and Debug Zombie objects in iOS using Xcode 5.1.1. That question explains how to use it, but you don’t need to run Instruments as mentioned there.
Then just run the app and Xcode will show you the reason of EXC_BAD_ACCESS. Don’t forget to turn Zombies off after you don’t need it.
The name Zombie comes from the fact that under this mode all deallocated objects will be marked and will be kept as special regions of memory (not live, not dead, zombies). Once your code attempts to use such deallocated object, Xcode will notice and print helpful message.

Related

Need help understanding a conditional crash when accessing my NSDictionary

I am keeping my data in a property called practiceRecords (an NSArray of dictionaries).
I check to see if the data already exists in the documents folder.
If yes, I load the data into self.practiceRecords.
If not, I build the array of dictionaries (using literal syntax), keeping this data in the self.practiceRecords property, and then write the data out to the documents folder.
(I am NOT reloading the data after writing it out)
As far as I am able to tell, there are no problems occurring during this process.
Then I have a step where I modify my data as follows ...
-(void)incNumberOfTriesFor:(NSString *)stringOfIndex {
if (self.practiceRecords)
{
int index = [stringOfIndex intValue];
int numberOfTries = [(NSNumber *)(self.practiceRecords[index][#"tries"]) intValue] + 1;
//CRASHING on this next line.
self.practiceRecords[index][#"tries"] = #(numberOfTries);
//message to helper method
[self writePracticeRecords];
}
}
So the first time through (when the array is built and written out) I get a crash at the indicated line.
The error is:
-[__NSDictionaryI setObject:forKeyedSubscript:]: unrecognized selector sent to instance
I quit the app, check the documents folder and see the data file written out with no issues.
I re-run the app, and then get no crash and the data file still looks great.
This is repeatable.
If the data file exists, no crash.
If the data first needs to be created, then a crash.
(In all cases, I manually look inside the resulting data file and see exactly what I expect to see - no issues there)
I'm not sure where to even begin squashing this bug, and would really like to understand the details of why this is happening.
Thanks very much for any help!
Just to recap the correct comments above:
-[__NSDictionaryI setObject:forKeyedSubscript:]: unrecognized selector sent to instance
NSDictionary does not implement any of the set... methods because it is immutable. You state that you're creating with literals syntax when the data is not found on disk. The literal syntax creates immutable containers
Instead, try...
// try to initialize from disk, but if not
// we can still use literal (immutable) syntax, but in a mutable container
self.practiceRecords = [NSMutableDictionary
dictionaryWithDictionary:#{ #"key" : #"value" }];

Thread 1 : EXC_BAD_ACCESS (Code = 1, address = 0x30000008)

I still stuck on this problem even followed all the answer from this forum. can anyone tell me what to do in simple way? I'm new learner in xcode. I have enable the zombie object.
this is my coding that got crash
if ([[[AryStoreknowItem objectAtIndex:indexPath.row] objectForKey:#"action"] isEqualToString:#"a1"]) {
NSString *t1 =[[AryStoreknowItem objectAtIndex:indexPath.row] objectForKey:#"title"];
NSString *a1 = [[AryStoreknowItem objectAtIndex:indexPath.row] objectForKey:#"action"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// saving an NSString
[defaults setObject:a1 forKey:#"a1"];
[defaults setObject:t1 forKey:#"t1"];
JournalPage *journal=[[JournalPage alloc]initWithNibName:#"JournalPage" bundle:nil];
[self presentModalViewController:journal animated:YES];
In my Application, I have multiple ViewController. when i click on back button of UINavigationBar then this type of issue generated , i can't explain my problem because all the functionality work proper.
Example :-
1 - fitstVController (work properly)
=> it have UITableView , when i click on specific row then it will be go on another UIViewController (SecoundViewController)
2 - SecoundViewController (work properly)
=> it have UITableView and UIActionSheet. when i select button of UiActionSheet then another UIViewController (ThirdViewController) is open
3 - ThirdViewController (cannot open)
=> error came when i click on row three. same goes if i click on other cell, the third cell that i click will got crash before in goes to other pages
I don’t think we've got enough here to diagnose any particular problem (and it’s hard to follow your description). Nonetheless, I would recommend:
I would suggest running your code through the static analyzer (shift+command+B or “Analyze” on the Xcode “Product” menu) and making sure that doesn't provide any warnings. That will (amongst other things) identify many routine memory issues that can easily plague non-ARC code. There's no point in going further until you get a clean bill of health here.
I would suggest turning on the Exception Breakpoint and see if that identifies a particular line of code that is the source of the issue. Sometimes that can identify the line of code without having to reverse engineer where the error occurred by looking at the stack trace.
Given that you're doing non-ARC code, you might also want to temporarily turn on zombies. You can see this setting the the Scheme Configuration settings.
Beyond that, I’d refer you to Ray Wenderlich article My App Crashed, Now What?.
If you continue to have errors, share the stack trace with us.
You might have dismissed a ViewController while an object is still accessing it. That was my issue and reading Rob's answer helped.
This type of problem usually happens due to memory release/allocation
Go to
Product -> Clean
will fix this problem in most cases
I got this error when I was utilizing a reusable view /XIB and had the combination of two errors:
I forgot to specify the name of the custom class in the identity inspector
I cast the view as my specific view class in its outlet
Specifying the view class in the Identity Inspector corrected the error

My NSDictionary somehow has multiple values for one key

I have been attempting to debug a issue with my code, and just came upon an odd phenomenon. Found this in the debug area when a breakpoint was triggered:
Am I correct in observing that there are multiple values for this key: #"6898173"??
What are possible causes of this? I do not set those key-value pairs using the string literal, but by getting a substring of a string retrieved and decoded from a GKSession transmission.
I still have this up in the debug area in xcode, incase theres anything else there that might help.
EDIT:
By request, here is the code that would have created one of the two strings (another was created at an earlier time):
[carForPeerID setObject:[[MultiScreenRacerCarView alloc] initWithImage:[UIImage imageNamed:#"simple-travel-car-top_view"] trackNumber:[[[NSString stringWithUTF8String:data.bytes] substringWithRange:range] intValue]] forKey:[[NSString stringWithUTF8String:[data bytes]] substringFromIndex:9]];
The string in data might look something like this:
car00.0146898173
EDIT:
Code that sends the data:
[self.currentSession sendData:[[NSString stringWithFormat:#"car%i%#%#", [(MultiScreenRacerCarView *)[carForPeerID objectForKey:peerID] trackNumber], speed, [(MultiScreenRacerCarView *)[carForPeerID objectForKey:peerID] owner]] dataUsingEncoding:NSUTF8StringEncoding] toPeers:#[(NSString *)[peersInOrder objectAtIndex:(self.myOrderNumber + 1)]] withDataMode:GKSendDataReliable error:nil];
Sorry its hard to read. Its only one line.
What you're seeing is a debugger "feechure". When you have a mutable dictionary and modify it, the debugger may not show you the correct view of the object.
To reliably display the contents of an NSMutableArray or NSMutableDictionary, switch to the console and type po carForPeerID.

IOS: Release for NSString is not working as expected

I found a strange behavior with NSString. I tried to run the below code and noticed this.
NSString *str = [[NSString alloc] initwithstring : #"hello"];
[str release];
NSLog(#" Print the value : %#", str);
Here, in the third line app should crash because we are accessing an object which is released. But it is printing the value of str. It is not crashing. But with NSArray i observed different behavior.
NSArray *array = [[NSArray alloc] initwithobjects : #"1", #"2", nil];
[array release];
NSLog(#"Print : %#", [array objectatindex : 0]);
NSLog(#"Print : %#", [array objectatindex : 0]);
The code has two NSLog statements used for NSArray. Here after releasing when the first NSLog is executed, it is printing value. But when second NSLog is executed, app crashes. App crash is acceptable because the array accessed was released already. But it should crash when the first NSLog is executed. Not the second one.
Help me with this behaviors. How release works in these cases.
Thanks
Jithen
The first example doesn't crash because string literals are never released. The code is really:
NSString *str = #"hello";
[str release];
People get burned with string literals on memory management and mistakenly using == to compare them instead of isEqualToString:. The compiler does some optimizations that lead to misleading results.
Update:
The following code proves my point:
NSString *literal = #"foo";
NSString *second = [NSString stringWithString:literal];
NSString *third = [NSString stringWithString:#"foo"]; // <-- this gives a compiler warning for being redundant
NSLog(#"literal = %p", literal);
NSLog(#"second = %p", second);
NSLog(#"third = %p", third);
This code gives the following output:
2013-02-28 22:03:35.663 SelCast[85617:11303] literal = 0x359c
2013-02-28 22:03:35.666 SelCast[85617:11303] second = 0x359c
2013-02-28 22:03:35.668 SelCast[85617:11303] third = 0x359c
Notice that all three variable point to the same memory.
Your second example crashes at the second NSLog because at the first log, the memory where array was hasn't been re-used, but that first log causes enough activity on the heap to cause the memory to become used by something else. Then, when you try to access it again, you get a crash.
Whenever an object is deallocated and its memory marked as free, there is going to be some period of time where that memory still stores what's left of that object. During this time you can still call methods on such objects and so forth, without crashing. This time is extremely short, and if you're running a lot of threads it may not even be enough to get your method call in. So clearly, don't rely on this implementation detail for any behavior.
As others have said, regarding your first question, NSString literals aren't going to be deallocated. This is true for some other Foundation classes (NSNumber comes to mind) but is an implementation detail as well. If you need to do experiments on memory management, use an NSObject instance instead, as it will not show the unusual behaviors.
When you send a release message on an object, the object is actually not being removed from the memory. The release message simply decrements the reference count by one only. If the reference count is zero the object is marked as free. Then the system remove it from the memory. Until this deallocation happens you can access your object. Even if you release the object your object pointer still points to the object unless you are assigning nil to the pointer.
The first example doesn't crash because string literals are never released. Where the second totally depends on release and retain counter.
Read this article. Its contains short-and-sweet explanation for your query
You Should read this apple guideline
You seem to assume that release should destroy the object immediately. I don't think that's the guarantee that the language makes. What release means is: I have finished using this object and I promise not to use it again. From that point onwards it's up to the system to decide when to actually deallocate the memory.
Any behaviour you see beyond that is not defined and may change from one version of the Objective C runtime to the next.
That's to say that the other answers that suggest the difference is string literals and re-use of memory are currently correct but assuming that the behaviour will always be like this would likely be a mistake.

Object sent -autorelease too many times (iOS5)

I've struck a problem using the latest XCode beta (4.2 Build 4C114, iOS 5.0) and autorelease that I can't solve. The code needs to conditionally set a string which will be the message in an alert:
NSString* msg = ([result rangeOfString:#"Ok"].location == NSNotFound) ?
#"Upload failed" : #"Uploaded ok";
Running Analyze highlights the line saying "Object sent -autorelease too many times (2)".
And sho'nuf, running the app (under the Simulator) causes a SIGABRT double free.
I've tried coding the line as an if/else.
I've tried creating separate strings for the two messages and just assigning the appropriate pointer to a third pointer with the ternary and if/else.
Nothing I do makes this go away!
Creating a string with #"string contents" will always be autoreleased automatically. You don't need to specifically release it yourself.
In most cases you would only need to release an object if you called "alloc" or "new" on it to begin with.

Resources