{
"restaurants" : [
{
"name": "Hopdoddy Burger Bar",
"backgroundImageURL": "http://sandbox.bottlerocketapps.com/BR_iOS_CodingExam_2015_Server/Images/hopdoddy.png",
"category" : "Burgers",
"contact": {
"phone": "9723872337",
"formattedPhone": "(972) 387-2337",
"twitter": "hopdoddy"
},
"location": {
"address": "5100 Belt Line Road, STE 502",
"crossStreet": "Dallas North Tollway",
"lat": 32.950787,
"lng": -96.821118,
"postalCode": "75254",
"cc": "US",
"city": "Addison",
"state": "TX",
"country": "United States",
"formattedAddress": [
"5100 Belt Line Road, STE 502 (Dallas North Tollway)",
"Addison, TX 75254",
"United States"
]
}
},
{
"name": "Pappadeaux Seafood Kitchen",
"backgroundImageURL": "http://sandbox.bottlerocketapps.com/BR_iOS_CodingExam_2015_Server/Images/pappadeaux.png",
"category": "Seafood",
"contact": {
"phone": "9724479616",
"formattedPhone": "(972) 447-9616",
"twitter": "pappadeaux"
},
"location": {
"address": "18349 Dallas Pkwy",
"crossStreet": "at Frankford Rd.",
"lat": 32.99908456526653,
"lng": -96.83018780592823,
"postalCode": "75287",
"cc": "US",
"city": "Dallas",
"state": "TX",
"country": "United States",
"formattedAddress": [
"18349 Dallas Pkwy (at Frankford Rd.)",
"Dallas, TX 75287",
"United States"
]
}
},
{
"name": "Buffalo Wild Wings",
"backgroundImageURL": "http://sandbox.bottlerocketapps.com/BR_iOS_CodingExam_2015_Server/Images/buffalo_wild_wings.png",
"category": "Wing Joint",
"contact": {
"phone": "9727019464",
"formattedPhone": "(972) 701-9464",
"twitter": "bwwings"
},
"location": {
"address": "5000 Belt Line Rd Ste 100",
"crossStreet": "at Quorum Dr",
"lat": 32.95347617827522,
"lng": -96.82554602622986,
"postalCode": "75254-6752",
"cc": "US",
"city": "Dallas",
"state": "TX",
"country": "United States",
"formattedAddress": [
"5000 Belt Line Rd Ste 100 (at Quorum Dr)",
"Dallas, TX 75254-6752",
"United States"
]
}
}
]
}
This is the JSON I am trying to parse in iOS. I have created my Model objects with all the required parameters. I am able to parse and fetch all the data except for the backgroundImageURL. I get a NSUnknownKeyException. Can someone help me with this?
Below is the code used for creating the Model objects and adding them to an array.
[self.restaurantsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Restaurant *restaurant = [[Restaurant alloc]init];
restaurant.name = [obj objectForKey:#"name"];
restaurant.imageURL = [obj objectForKey:#"backgroundImageURL"];
restaurant.category = [obj objectForKey:#"category"];
restaurant.contact = [obj objectForKey:#"contact"];
restaurant.location = [obj objectForKey:#"location"];
[self.parsedRestaurantArray addObject:restaurant];
}];
This is the Restaurant class:
#interface Restaurant : NSObject
#property (nonatomic, strong)NSString *name;
#property (nonatomic, strong)NSString *imageURL;
#property (nonatomic, strong)NSString *category;
#property (nonatomic, strong)Contact *contact;
#property (nonatomic, strong)Location *location;
#end
Here is the track trace:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key backgroundImageURL.'
*** First throw call stack:
(
0 CoreFoundation 0x000000010e631e65 exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010e0aadeb objc_exception_throw + 48
2 CoreFoundation 0x000000010e631aa9 -[NSException raise] + 9
3 Foundation 0x000000010dd0a888 -[NSObject(NSKeyValueCoding) valueForUndefinedKey:] + 226
4 Foundation 0x000000010dc60997 -[NSObject(NSKeyValueCoding) valueForKey:] + 280
5 Foundation 0x000000010dc60758 -[NSArray(NSKeyValueCoding) valueForKey:] + 437
6 BottleRocketExercise 0x000000010cd8692a -[LunchesViewController collectionView:cellForItemAtIndexPath:] + 282
7 UIKit 0x000000010f2335ba -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:] + 483
8 UIKit 0x000000010f235ae0 -[UICollectionView _updateVisibleCellsNow:] + 4431
9 UIKit 0x000000010f23a23b -[UICollectionView layoutSubviews] + 247
10 UIKit 0x000000010ea954a3 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 703
11 QuartzCore 0x00000001129a759a -[CALayer layoutSublayers] + 146
12 QuartzCore 0x000000011299be70 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
13 QuartzCore 0x000000011299bcee _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
14 QuartzCore 0x0000000112990475 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 277
15 QuartzCore 0x00000001129bdc0a _ZN2CA11Transaction6commitEv + 486
16 QuartzCore 0x00000001129be37c _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92
17 CoreFoundation 0x000000010e55d367 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 23
18 CoreFoundation 0x000000010e55d2d7 __CFRunLoopDoObservers + 391
19 CoreFoundation 0x000000010e552f2b __CFRunLoopRun + 1147
20 CoreFoundation 0x000000010e552828 CFRunLoopRunSpecific + 488
21 GraphicsServices 0x000000011245cad2 GSEventRunModal + 161
22 UIKit 0x000000010e9de610 UIApplicationMain + 171
23 BottleRocketExercise 0x000000010cd85f5f main + 111
24 libdyld.dylib 0x00000001106f192d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
I think the problem with your code is that you have and array of restaurants and not just one restaurant. Your obj has not the keys because it has arrays of restaurants. You can only get the keys of each restaurant.
Related
I'm developing a react-native application, I use import Share from 'react-native-share'; for sharing files.
When it open share modal on iOS and I choose Save to File ( for examples a pdf file ) it thrown this execption:
{
"code": "ENSCOCOAERRORDOMAIN3072",
"message": "The operation was cancelled.",
"nativeStackIOS": [
"0 MyApp 0x0000000109361a97 RCTJSErrorFromCodeMessageAndNSError + 135",
"1 MyApp 0x00000001093619c3 RCTJSErrorFromNSError + 275",
"2 MyApp 0x00000001092e8c81 __41-[RCTModuleMethod processMethodSignature]_block_invoke_4.110 + 161",
"3 MyApp 0x0000000109242696 __48-[RNShare open:failureCallback:successCallback:]_block_invoke_2 + 214",
"4 ShareSheet 0x00007fff4310eec7 __68-[UIActivityViewController _cleanupActivityWithSuccess:items:error:]_block_invoke + 183",
"5 UIKitCore 0x00007fff46e15f25 -[UIPresentationController transitionDidFinish:] + 978",
"6 UIKitCore 0x00007fff46e1aa61 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke.503 + 199",
"7 UIKitCore 0x00007fff46f32e2c -[_UIViewControllerTransitionContext completeTransition:] + 88",
"8 UIKitCore 0x00007fff47a0c180 -[UITransitionView notifyDidCompleteTransition:] + 247",
"9 UIKitCore 0x00007fff47a0be03 -[UITransitionView _didCompleteTransition:] + 1423",
"10 UIKitCore 0x00007fff47a45f20 -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] + 671",
"11 UIKitCore 0x00007fff47a16a11 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 268",
"12 UIKitCore 0x00007fff47a16f83 -[UIViewAnimationState animationDidStop:finished:] + 259",
"13 UIKitCore 0x00007fff47a1710a -[UIViewAnimationState animationDidStop:finished:] + 650",
"14 QuartzCore 0x00007fff2b080ac2 _ZN2CA5Layer23run_animation_callbacksEPv + 306",
"15 libdispatch.dylib 0x00007fff516ad781 _dispatch_client_callout + 8",
"16 libdispatch.dylib 0x00007fff516b9caa _dispatch_main_queue_callback_4CF + 1212",
"17 CoreFoundation 0x00007fff23b0ce49 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9",
"18 CoreFoundation 0x00007fff23b07aa9 __CFRunLoopRun + 2329",
"19 CoreFoundation 0x00007fff23b06e66 CFRunLoopRunSpecific + 438",
"20 GraphicsServices 0x00007fff38346bb0 GSEventRunModal + 65",
"21 UIKitCore 0x00007fff47578dd0 UIApplicationMain + 1621",
"22 MyApp 0x0000000109117201 main + 97",
"23 libdyld.dylib 0x00007fff516ecd29 start + 1",
"24 ??? 0x0000000000000001 0x0 + 1"
],
"domain": "NSCocoaErrorDomain",
"userInfo": {}
}
My .apib document has the following response defined:
21 + Response 200 (application/json)
22
23 + Body
24
25 {
26 "Datetime: "2017-04-23T18:25:43.700Z",
27 "UserId": "1",
28 "Goal": "25",
29 "MaxReps": "8",
30 "Workout":
31 [
32 {
33 "SequenceNo": "1",
34 "Action": "Pullups",
35 "Units": "3"
36 },
37 {
38 "SequenceNo": "2",
39 "Action": "Rest",
40 "Units": "60"
41 },
42 {
43 "SequenceNo": "3",
44 "Action": "Pullups",
45 "Units": "5"
46 },
47 {
48 "SequenceNo": "4",
49 "Action": "Rest",
50 "Units": "60"
51 },
52 {
53 "SequenceNo": "5",
54 "Action": "Pullups",
55 "Units": "4"
56 }
57 ]
58 }
However it fails when running dredd with the error:
warn: Parser warning in file '/root/pullapi/api-description.apib': (warning code 10) message-body asset is expected to be a pre-formatted cod
e block, every of its line indented by exactly 12 spaces or 3 tabs on lines 25-58
However this matches the structure in the apiblueprint examples.
Any idea of what I'm doing wrong?
Simply indented the body by 12 spaces:
21 + Response 200 (application/json)
22
23 + Body
24
25 {
26 "Datetime: "2017-04-23T18:25:43.700Z",
27 "UserId": "1",
28 "Goal": "25",
29 "MaxReps": "8",
30 "Workout":
31 [
32 {
33 "SequenceNo": "1",
34 "Action": "Pullups",
35 "Units": "3"
36 },
37 {
38 "SequenceNo": "2",
39 "Action": "Rest",
40 "Units": "60"
41 },
42 {
43 "SequenceNo": "3",
44 "Action": "Pullups",
45 "Units": "5"
46 },
47 {
48 "SequenceNo": "4",
49 "Action": "Rest",
50 "Units": "60"
51 },
52 {
53 "SequenceNo": "5",
54 "Action": "Pullups",
55 "Units": "4"
56 }
57 ]
58 }
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.
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;
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.