[__NSDictionaryI bytes]: unrecognized selector sent to instance 0x7faa75501220 - ios
I want to get the json data to a block, but it failed.
the Internet request is
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *dataResult, NSError *connectionError) {
if (!connectionError) {
if (successBlock) {
//NSString* str = [[NSString alloc] initWithData:dataResult encoding:NSUTF8StringEncoding];
//NSLog(#"response data: %#", str);
NSDictionary *json = [[NSDictionary alloc]init];
json = [NSJSONSerialization JSONObjectWithData:dataResult options:kNilOptions error:nil];
successBlock(json);
}
} else {
if (failureBlock) {
failureBlock(connectionError);
}
}
}];
the successBlock is defined like this:
typedef void(^HttpRequestSuccessBlock)(id responseObject);
typedef void(^HttpRequestFailBlock)(NSError *error);
I can successfully get the dataResult in 1 and translate it into NSString, and I NSlog it, it is actually the Json format.
But when run the code, it crashed and shows the following errors:
2017-08-21 09:43:22.258 shopiPhoneDemo[24397:5799646] -[__NSDictionaryI bytes]: unrecognized selector sent to instance 0x7faa75501220
2017-08-21 09:43:22.264 shopiPhoneDemo[24397:5799646] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI bytes]: unrecognized selector sent to instance 0x7faa75501220'
Update the stack trace:
2017-08-21 09:43:22.258 shopiPhoneDemo[24397:5799646] -[__NSDictionaryI bytes]: unrecognized selector sent to instance 0x7faa75501220
2017-08-21 09:43:22.264 shopiPhoneDemo[24397:5799646] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI bytes]: unrecognized selector sent to instance 0x7faa75501220'
*** First throw call stack:
(
0 CoreFoundation 0x0000000105e8cb0b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x00000001058f1141 objc_exception_throw + 48
2 CoreFoundation 0x0000000105efc134 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x0000000105e13840 ___forwarding___ + 1024
4 CoreFoundation 0x0000000105e133b8 _CF_forwarding_prep_0 + 120
5 Foundation 0x00000001054281a1 -[_NSJSONReader findEncodingFromData:withBOMSkipLength:] + 46
6 Foundation 0x0000000105428087 -[_NSJSONReader parseData:options:] + 58
7 Foundation 0x0000000105427fbb +[NSJSONSerialization JSONObjectWithData:options:error:] + 139
8 shopiPhoneDemo 0x0000000104cc4e2d __24-[AppDelegate youtuTest]_block_invoke + 77
9 shopiPhoneDemo 0x0000000104cbfc3f __62-[TXQcloudFrSDK sendRequest:mothod:successBlock:failureBlock:]_block_invoke + 271
10 CFNetwork 0x0000000108a045ae __67+[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]_block_invoke_2 + 161
11 Foundation 0x00000001053fb3b7 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 7
12 Foundation 0x00000001053fb0bb -[NSBlockOperation main] + 101
13 Foundation 0x00000001053f9877 -[__NSOperationInternal _start:] + 627
14 Foundation 0x00000001053f55fc __NSOQSchedule_f + 198
15 libdispatch.dylib 0x000000010940905c _dispatch_client_callout + 8
16 libdispatch.dylib 0x00000001093ea40b _dispatch_main_queue_callback_4CF + 411
17 CoreFoundation 0x0000000105e51909 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
18 CoreFoundation 0x0000000105e17ae4 __CFRunLoopRun + 2164
19 CoreFoundation 0x0000000105e17016 CFRunLoopRunSpecific + 406
20 GraphicsServices 0x000000010b4bba24 GSEventRunModal + 62
21 UIKit 0x0000000106999134 UIApplicationMain + 159
22 shopiPhoneDemo 0x0000000104cd0eff main + 111
23 libdyld.dylib 0x000000010945565d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
the Json NSLog is:
{"errorcode":0,"errormsg":"OK","session_id":"","name":"陈佳佳","name_confidence_all":[99,99,99],"sex":"女","sex_confidence_all":[99],"nation":"汉","nation_confidence_all":[99],"birth":"1985/9/11","birth_confidence_all":[100,100,100,100,100,100,100,100,100],"address":"福建省尤溪县汤川乡汤三村16号","address_confidence_all":[99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],"id":"350426198509113027","id_confidence_all":[100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100],"frontimage":"","frontimage_confidence_all":[],"watermask_confidence_all":[],"valid_date_confidence_all":[],"authority_confidence_all":[],"backimage_confidence_all":[],"detail_errorcode":[],"detail_errormsg":[]}
I use json editor format is:
{
"errorcode": 0,
"errormsg": "OK",
"session_id": "",
"name": "陈佳佳",
"name_confidence_all": [
99,
99,
99
],
"sex": "女",
"sex_confidence_all": [
99
],
"nation": "汉",
"nation_confidence_all": [
99
],
"birth": "1985/9/11",
"birth_confidence_all": [
100,
100,
100,
100,
100,
100,
100,
100,
100
],
"address": "福建省尤溪县汤川乡汤三村16号",
"address_confidence_all": [
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99
],
"id": "350426198509113027",
"id_confidence_all": [
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100
],
"frontimage": "",
"frontimage_confidence_all": [],
"watermask_confidence_all": [],
"valid_date_confidence_all": [],
"authority_confidence_all": [],
"backimage_confidence_all": [],
"detail_errorcode": [],
"detail_errormsg": []
}
What I have tried to do:
I try to make a mutablecopy for json, but it doesn't working.
I try to change the id into NSDictionary, but it doesn't working either.
Might be you are dealing with NSArray rather than NSDictionary. So it's better to handle both of the cases.
id json = [NSJSONSerialization JSONObjectWithData:dataResult options:kNilOptions error:nil];
if ([json isKindOfClass:[NSArray class]]) {
NSLog(#"its an array!");
NSArray *jsonArray = (NSArray *)json;
NSLog(#"jsonArray - %#",jsonArray);
}
else {
NSLog(#"its probably a dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)json;
NSLog(#"jsonDictionary - %#",jsonDictionary);
}
I think problem inside the data or inside the json parcer. Try to use other json parser with open code, for example https://github.com/johnezang/JSONKit/blob/master/JSONKit.h. You can find, what exactly sends this exception.
Related
Download JSON async crash
I download my Firebase database in json with AFNetworking 3. Everything works fine but there is a crash in the function cellForRoAtIndexPath. Thanks Work : AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; [manager GET:#"https://jojol-concours-lists.firebaseio.com/.json" parameters:URLParameters progress:nil success:^(NSURLSessionTask *task, id responseObject) { self.contestArray = responseObject; [_collectionView reloadData]; } failure:^(NSURLSessionTask *operation, NSError *error) { NSLog(#"Error: %#", error); }]; Work : - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return [self.contestArray count]; } Not work : (NSDictionary *array = [self.contestArray objectAtIndex:indexPath.row];) - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { DemoCollectionViewCell *retVal = [collectionView dequeueReusableCellWithReuseIdentifier:#"collectionViewCell" forIndexPath:indexPath]; //////// Not work /////// NSDictionary *array = [self.contestArray objectAtIndex:indexPath.row]; //////// Not work /////// retVal.name.text = #""; retVal.contentView.layer.cornerRadius = 10; retVal.contentView.layer.masksToBounds = YES; return retVal; } JSON : { "Concours-1" : { "Description" : "Description du concours", "Title" : "Titre" }, "Concours-2" : { "Description" : "Description du concours", "Titre" : "iPhone 6" } } Log Crash : -[NSDictionaryI objectAtIndex:]: unrecognized selector sent to instance 0x61000086c8c0 2017-07-18 10:00:26.787 jojol67[7003:4420828] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI objectAtIndex:]: unrecognized selector sent to instance 0x61000086c8c0' *** First throw call stack: ( 0 CoreFoundation 0x000000010c084b0b __exceptionPreprocess + 171 1 libobjc.A.dylib 0x000000010e5c9141 objc_exception_throw + 48 2 CoreFoundation 0x000000010c0f4134 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132 3 CoreFoundation 0x000000010c00b840 ___forwarding_ + 1024 4 CoreFoundation 0x000000010c00b3b8 _CF_forwarding_prep_0 + 120 5 jojol67 0x000000010756db3f -[DEMOConcoursTableViewController collectionView:cellForItemAtIndexPath:] + 191 6 UIKit 0x000000010d162925 -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:] + 446 7 UIKit 0x000000010d162761 -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:] + 35 8 UIKit 0x000000010d1679bd -[UICollectionView _updateVisibleCellsNow:] + 4764 9 UIKit 0x000000010d16d38e -[UICollectionView layoutSubviews] + 313 10 UIKit 0x000000010c8f355b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1268 11 QuartzCore 0x000000010c6a4904 -[CALayer layoutSublayers] + 146 12 QuartzCore 0x000000010c698526 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 370 13 QuartzCore 0x000000010c6983a0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24 14 QuartzCore 0x000000010c627e92 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294 15 QuartzCore 0x000000010c654130 _ZN2CA11Transaction6commitEv + 468 16 QuartzCore 0x000000010c654b37 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 115 17 CoreFoundation 0x000000010c02a717 CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 23 18 CoreFoundation 0x000000010c02a687 __CFRunLoopDoObservers + 391 19 CoreFoundation 0x000000010c00f720 __CFRunLoopRun + 1200 20 CoreFoundation 0x000000010c00f016 CFRunLoopRunSpecific + 406 21 GraphicsServices 0x00000001103c2a24 GSEventRunModal + 62 22 UIKit 0x000000010c830134 UIApplicationMain + 159 23 jojol67 0x000000010752ef5f main + 111 24 libdyld.dylib 0x000000010f31d65d start + 1 25 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException /////// Firebase realtime database ////////
Your id responseObject is not an array because your JSON contains an object not an array. App crashes because you are calling objectAtIndex on a NSDictionary object. If you want to access this JSON as an array, you may want to format it to something like this, [{ "Concours": 1, "Description": "Description du concours", "Title": "Titre" }, { "Concours": 2, "Description": "Description du concours", "Titre": "iPhone 6" }]
It will help you for such responce: NSDictionary *jsonDict =responseObject; NSArray *allKeys = [jsonDict allKeys]; NSMutableArray *allDataArray = [NSMutableArray new]; for (int x = 0; x<allKeys.count; x++) { NSString *key = [allKeys objectAtIndex:x]; [allDataArray addObject:[jsonDict valueForKey:key]]; // then reload your collection on allDataArray }
Current JSON: { "Concours-1" : { "Description" : "Description du concours", "Title" : "Titre" }, "Concours-2" : { "Description" : "Description du concours", "Titre" : "iPhone 6" } } How it should be: [ { "Description": "Description du concours", "Title": "Titre" }, { "Description": "Description du concours", "Titre": "iPhone 6" } ]
"-[NSDictionaryI objectAtIndex:]: unrecognized selector sent to instance 0x61000086c8c0 " It seems that the self.contestArray is NSDictionary class; You can log the responseObject it maybe a Dictionary , not Array;
How to get all values of one specific key from an array?
I am developing application using Objective C. I am getting following array in the response from server side ( i'm using Get method of AFNetworking). Response from server: `[{"name":"option1","profile_id":0,"profile_name":"option1"},{"name":"option2","profile_id":0,"profile_name":"option2"},{"name":"option3","profile_id":0,"profile_name":"option3"},{"name":"option4","profile_id":0,"profile_name":"option4"},{"name":"option5","profile_id":0,"profile_name":"option5"},{"name":"option6","profile_id":0,"profile_name":"option6"},{"name":"option7","profile_id":0,"profile_name":"option7"},{"name":"option8","profile_id":0,"profile_name":"option8"},{"name":"option9","profile_id":0,"profile_name":"option9"},{"name":"option10","profile_id":0,"profile_name":"option10"}]` I want to separate values for the key name. In short, i want output like:[option1,option2,option3,option4,option5,option6,option7,option8,option9,option10] For that i tried like following way: store that response in array (_arr). and then try to separate values for key name like following way, NSArray *optionArray = [_arr valueForKey:#"name"]; NSLog(#"%#",optionArray); but, unfortunately this is not working. Application crashes and gives following logs. Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x7abd0600> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.' *** First throw call stack: ( 0 CoreFoundation 0x00ae2a14 __exceptionPreprocess + 180 1 libobjc.A.dylib 0x005a3e02 objc_exception_throw + 50 2 CoreFoundation 0x00ae2631 -[NSException raise] + 17 3 Foundation 0x00239098 -[NSObject(NSKeyValueCoding) valueForUndefinedKey:] + 282 4 Foundation 0x0017a798 _NSGetUsingKeyValueGetter + 105 5 Foundation 0x0017a727 -[NSObject(NSKeyValueCoding) valueForKey:] + 288 6 Foundation 0x001bac40 -[NSFunctionExpression expressionValueWithObject:context:] + 1079 7 Foundation 0x001ba739 -[NSComparisonPredicate evaluateWithObject:substitutionVariables:] + 290 8 Foundation 0x001ba60f -[NSPredicate evaluateWithObject:] + 48 9 Foundation 0x001ba593 _filterObjectsUsingPredicate + 437 10 Foundation 0x001ba360 -[NSArray(NSPredicateSupport) filteredArrayUsingPredicate:] + 314 11 Wellness_24x7 0x0008fbc4 __31-[ForthViewController Donating]_block_invoke + 564 12 Wellness_24x7 0x0006c097 __116-[AFHTTPSessionManager dataTaskWithHTTPMethod:URLString:parameters:uploadProgress:downloadProgress:success:failure:]_block_invoke97 + 231 13 Wellness_24x7 0x00080bd5 __72-[AFURLSessionManagerTaskDelegate URLSession:task:didCompleteWithError:]_block_invoke_2132 + 213 14 libdispatch.dylib 0x0330e377 _dispatch_call_block_and_release + 15 15 libdispatch.dylib 0x033319cd _dispatch_client_callout + 14 16 libdispatch.dylib 0x03316f90 _dispatch_main_queue_callback_4CF + 910 17 CoreFoundation 0x00a33fde __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 14 18 CoreFoundation 0x009f1cd4 __CFRunLoopRun + 2356 19 CoreFoundation 0x009f10e6 CFRunLoopRunSpecific + 470 20 CoreFoundation 0x009f0efb CFRunLoopRunInMode + 123 21 GraphicsServices 0x050c8664 GSEventRunModal + 192 22 GraphicsServices 0x050c84a1 GSEventRun + 104 23 UIKit 0x012ecbfa UIApplicationMain + 160 24 Wellness_24x7 0x0006905a main + 138 25 libdyld.dylib 0x0335ba21 start + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException Thank you in advance.
actually your JSON Response started with Array, so do like NSArray *ResponseArray = [NSJSONSerialization JSONObjectWithData: data options: KNilOptions error: nil]; NSMutableArray *finalArray = [NSMutableArray array]; for (NSDictionary *temp in ResponseArray) { [finalArray addObject:temp[#"name"]]; } Choice-2 for AFNetworking NSMutableArray *finalArray = [NSMutableArray array]; for (NSDictionary *temp in responseObject) { [finalArray addObject:temp[#"name"]]; }
Try this NSMutableArray *arrOptions = [NSMutableArray new]; for (int i=0; i<_arr.count; i++) { [arrOptions addObject:[[_arr objectAtIndex:i] objectForKey:#"name"]]; } here arrOptions will contain your desired output.
I can see that you are getting response in JSON format. So you can convert JSON into mutable containers like Dictionary and Arrays. In your case it is array of dictionaries. NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e]; if(!jsonArray) { for(NSDictionary *dict in jsonArray) { NSLog(#"%#", dict valueForKey: #"name"); } }
According to your JSON data below you need to store data using NSDictionary instead of an Array. [{ "name": "option1", "profile_id": 0, "profile_name": "option1" }, { "name": "option2", "profile_id": 0, "profile_name": "option2" }, { "name": "option3", "profile_id": 0, "profile_name": "option3" }, { "name": "option4", "profile_id": 0, "profile_name": "option4" }, { "name": "option5", "profile_id": 0, "profile_name": "option5" }, { "name": "option6", "profile_id": 0, "profile_name": "option6" }, { "name": "option7", "profile_id": 0, "profile_name": "option7" }, { "name": "option8", "profile_id": 0, "profile_name": "option8" }, { "name": "option9", "profile_id": 0, "profile_name": "option9" }, { "name": "option10", "profile_id": 0, "profile_name": "option10" }] Get the data using dict like: NSDictionary *jsonDataDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSArray *optionArray = [jsonDataDict valueForKey:#"name"]; Problem: you are trying to get data of name key and you storing whole JSON data inside an array. Array doesn't contain key value pair use NSDictionary.
What you want to achieve and your thinking i can say you are on right track. You have converted your response Data in NSDictionary but it must be an array. NSArray *responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; this will convert your response to array and you can use NSArray *optionArray = [responseArray valueForKey:#"name"]; This will lead to same result as answer from #Krishna Kumar but with this you will be able to avoid "for" loop.
Deleting Selected row in UITableview when Button click
I'm getting an Exception while using removeObjectAtIndex. I've searched in this forum but I haven't found the correct solution for this Exception. Actually, I'm getting the data from server when I click on button, I'm getting success and also I need to delete that row but the selected row is not deleting. My Exception:- Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object' *** First throw call stack: ( 0 CoreFoundation 0x000000010cfd1c65 __exceptionPreprocess + 165 1 libobjc.A.dylib 0x000000010c46bbb7 objc_exception_throw + 45 2 CoreFoundation 0x000000010cfd1b9d +[NSException raise:format:] + 205 3 CoreFoundation 0x000000010cfca70e -[__NSCFArray removeObjectAtIndex:] + 94 4 SkigitApplication 0x00000001097fab80 __20-[HomePage Confirm:]_block_invoke + 272 5 SkigitApplication 0x00000001098c8628 __64-[AFHTTPRequestOperation setCompletionBlockWithSuccess:failure:]_block_invoke46 + 40 6 libdispatch.dylib 0x000000011160f186 _dispatch_call_block_and_release + 12 7 libdispatch.dylib 0x000000011162e614 _dispatch_client_callout + 8 8 libdispatch.dylib 0x0000000111616a1c _dispatch_main_queue_callback_4CF + 1664 9 CoreFoundation 0x000000010cf391f9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 9 10 CoreFoundation 0x000000010cefadcb __CFRunLoopRun + 2043 11 CoreFoundation 0x000000010cefa366 CFRunLoopRunSpecific + 470 12 GraphicsServices 0x000000010db6da3e GSEventRunModal + 161 13 UIKit 0x000000010acf7900 UIApplicationMain + 1282 14 SkigitApplication 0x00000001098c65bf main + 111 15 libdyld.dylib 0x0000000111663145 start + 1 16 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException Here is my code: request is my array In .h NSMutableArray *request; In .m -(void)Confirm:(id)sender { NSString *test = [NSString stringWithFormat:#"WebserviceUrl"]; AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [manager GET:test parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(#"JSON: %#", responseObject); if([[responseObject valueForKey:#"Success"]integerValue]) { request=[[responseObject valueForKey:#"info"]mutableCopy]; NSLog(#"array=%#",request); frndcount=[[[request valueForKey:#"is_new"]objectAtIndex:0]mutableCopy]; NSLog(#"frndcount=%#",frndcount); notification_id= [[[request valueForKey:#"notification_id"]objectAtIndex:0]mutableCopy]; NSLog(#"notification_id=%#",notification_id); item_id= [[[request valueForKey:#"item_id"]objectAtIndex:0]mutableCopy];; NSLog(#"item_id=%#",item_id); frnd_count.text=[NSString stringWithFormat:#"%#",frndcount]; if (deleteIndexPath==0) { [request removeObjectAtIndex:deleteIndexPath.row]; [self.msg_table deleteRowsAtIndexPaths:[NSArray arrayWithObject:deleteIndexPath] withRowAnimation:UITableViewRowAnimationFade]; } } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(#"Error: %#", error); }]; }
Your request object is a NSArray object, that is immutable. you should change it to NSMutableArray and your problem is resolved. Update I don't know how you are initialising this object, but if you are doing something like this: NSMutableArray *request = someData; the referencing object may be not mutable, so you should resolve it doing this: NSMutableArray *request = [someData mutableCopy]; Now, you have a mutable data.
NSMutableDictionary setobject: forkey: crashes with unrecognised selector message
For the below code snippet: error occurs at setObject: forKey: response <--is an NSDictionary if(response){ NSMutableArray *lifeArray = [[NSMutableArray alloc] init]; NSMutableDictionary *responseDict = [[NSMutableDictionary alloc] init]; responseDict = (NSMutableDictionary *)[response mutableCopy]; [responseDict setObject:#"life" forKey:#"label"]; <-- Error here } Note that variable responseDict is NSMutableDictionary since copied via mutableCopy. Error message: 2014-11-12 12:16:08.534 Lifetape[84381:508759] -[__NSCFArray setObject:forKey:]: unrecognized selector sent to instance 0x7a296700 2014-11-12 12:16:08.536 Lifetape[84381:508759] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray setObject:forKey:]: unrecognized selector sent to instance 0x7a296700' *** First throw call stack: ( 0 CoreFoundation 0x028fbdf6 __exceptionPreprocess + 182 1 libobjc.A.dylib 0x02557a97 objc_exception_throw + 44 2 CoreFoundation 0x02903a75 -[NSObject(NSObject) doesNotRecognizeSelector:] + 277 3 CoreFoundation 0x0284c9c7 ___forwarding___ + 1047 4 CoreFoundation 0x0284c58e _CF_forwarding_prep_0 + 14 5 Lifetape 0x000dfb83 __50-[LTTimeLineTableViewController getTimeIntervals:]_block_invoke + 307 6 Lifetape 0x0014cedb -[MethodInvoker maybeInvokeCallback] + 395 7 Lifetape 0x0014d19f -[MethodInvoker receiveResultWithError:andResult:] + 399 8 Lifetape 0x00143e38 -[MeteorClient(Connection) livedata_result:] + 1544 9 Lifetape 0x00138674 __54-[MeteorClient(Connection) initConnectionWithOptions:]_block_invoke_3 + 2660 10 Lifetape 0x0014b2b5 -[MeteorClient didReceiveMessage:] + 197 11 Lifetape 0x0014eb7d -[ObjectiveDDP webSocket:didReceiveMessage:] + 269 12 Lifetape 0x0015d986 __30-[SRWebSocket _handleMessage:]_block_invoke + 102 13 libdispatch.dylib 0x031e941a _dispatch_call_block_and_release + 15 14 libdispatch.dylib 0x03209e1f _dispatch_client_callout + 14 15 libdispatch.dylib 0x031f0981 _dispatch_main_queue_callback_4CF + 610 16 CoreFoundation 0x02855f3e __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 14 17 CoreFoundation 0x02814d40 __CFRunLoopRun + 2256 18 CoreFoundation 0x028141ab CFRunLoopRunSpecific + 443 19 CoreFoundation 0x02813fdb CFRunLoopRunInMode + 123 20 GraphicsServices 0x051a524f GSEventRunModal + 192 21 GraphicsServices 0x051a508c GSEventRun + 104 22 UIKit 0x00f41e16 UIApplicationMain + 1526 23 Lifetape 0x000ce36d main + 141 24 libdyld.dylib 0x03235ac9 start + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException
Here your response dictionary is a NSDictionary type collection so it does not have any selector like setObject, that's why it is giving you this error use if(response && [response isKindOfClass:[NSDictionary class]]){ NSMutableArray *lifeArray = [[NSMutableArray alloc] init]; NSMutableDictionary *responseDict = [NSMutableDictionary dictionaryWithDictionary:response]; [responseDict setObject:#"life" forKey:#"label"]; } and it will work but make sure response is your dictionary type object. as the error you have posted clearly says that your response is an array not a dictionary.
Your response looks like NSArray class so try below code. if([response isKindOfClass:[NSArray Class]]){ NSLog(#"Array"); } else if([response isKindOfClass:[NSDictionary Class]]){ NSLog(#"Dictionary"); } Now manage your code as per log.
[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance - source code and screenshot attached
At GitHub I have a simple iPhone app, which fetches user information (by using OAuth) from the social network Mail.ru: It does fetch and print the information, but then crashes. As an iOS programming newbie I'm confused by the output below (also please see the full output at PasteBin): 2014-01-21 21:21:10.873 oauthMailru[8228:3307] -[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance 0x8a97290 2014-01-21 21:21:10.875 oauthMailru[8228:3307] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance 0x8a97290' *** First throw call stack: ( 0 CoreFoundation 0x01aa65e4 __exceptionPreprocess + 180 1 libobjc.A.dylib 0x018298b6 objc_exception_throw + 44 2 CoreFoundation 0x01b43903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275 3 CoreFoundation 0x01a9690b ___forwarding___ + 1019 4 CoreFoundation 0x01a964ee _CF_forwarding_prep_0 + 14 5 oauthMailru 0x00003a62 __47-[ViewController fetchMailruWithToken:ForUser:]_block_invoke + 402 6 Foundation 0x01545695 __67+[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]_block_invoke_2 + 151 7 Foundation 0x014a5945 -[NSBlockOperation main] + 88 8 Foundation 0x014fe829 -[__NSOperationInternal _start:] + 671 9 Foundation 0x0147b558 -[NSOperation start] + 83 10 Foundation 0x01500af4 __NSOQSchedule_f + 62 11 libdispatch.dylib 0x021344b0 _dispatch_client_callout + 14 12 libdispatch.dylib 0x02121018 _dispatch_async_redirect_invoke + 202 13 libdispatch.dylib 0x021344b0 _dispatch_client_callout + 14 14 libdispatch.dylib 0x02122eeb _dispatch_root_queue_drain + 287 15 libdispatch.dylib 0x02123137 _dispatch_worker_thread2 + 39 16 libsystem_pthread.dylib 0x024c0dab _pthread_wqthread + 336 17 libsystem_pthread.dylib 0x024c4cce start_wqthread + 30 ) libc++abi.dylib: terminating with uncaught exception of type NSException Does anybody please know what's happening and how to read such crashes? My source files: ViewController.m, which displays UIWebView and then segues to DetailViewController.m
Your code thinks the JSON deserializes to an object (dictionary), but in fact it deserializes to an array containing one object. Try this: NSMutableArray *topLevelArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; NSDictionary *dict = topLevelArray[0]; If you want to check what you're getting, you can use isKindOfClass: like this: id jso = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; if (jso == nil) { // Error. You should probably have passed an NSError ** as the error // argument so you could log it. } else if ([jso isKindOfClass:[NSArray class]]) { NSArray *array = jso; // process array elements } else if ([jso isKindOfClass:[NSDictionary class]]) { NSDictionary *dict = jso; // process dictionary elements } else { // Shouldn't happen unless you use the NSJSONReadingAllowFragments flag. }