I created
NSArray *test = #[#[#1,#2,#3,#4], #[#3,#5,#6,#7]];
which will be considered as nsarray of nsarray.
but when I wanted to print it out with
NSLog (#"%#", test); or NSLog(#"%#", test[0]);
NSLog (#"%#", [test ObjectAtIndex: 0]);
the process always ends with
NSException; Signal SIGABRT
Reason: 'NSInvalidArgumentException', '-[__NSArrayI compare:]:unrecognized selector sent to instance 0x608000262788'
Please help me, could someone tell me how to deal with this problem? And in general how to debug theproblem 'Signal SIGABRT'?
SIGABRT means in general that there is an uncaught exception. There should be more information on the console.
I execute this code is my xcode, and it ran properly.
Take a look on this demo, Hope you get better knowledge
I use this code
NSArray *array = #[#"1111132324"];
NSLog(#"array : %#", array);
NSLog(#"array[0] : %#", array[0]);
and i get output:
as you see when I print array it gives output in braces '(' and ')'. If i print just single element of array which is string here, there is no braces.
As you said you have array in array, try like this
NSArray *arrayOuter = #[#"1111132324"];
NSArray *arrayInner = #[arrayOuter];
NSLog(#"array : %#", arrayInner);
NSLog(#"array[0] : %#", arrayInner[0]);
NSLog(#"array[0] : %#", arrayInner[0][0]);
see output:
You can extend your hierarchy of dictionary or array or mix of array-dictionary (doesn't matter) upto n times like this.
every key(for dict)/index(for array) is must be in that hierarchy level. Style of getting data is from upper hierarchy to lower hierarchy.
For dictionary
dict[#"key1"][#"key2"]...[#"keyN"]
for mix dict-arr
//upper object must be dictionary so start with key.
dict[#"key1"][0][#"key"]..[#"keyN"] or object index.
for mix array - dict
//upper object must be array so start with index.
dict[0][#"key1"][#"key"]..[#"keyN"] or object index.
NOTE: Sequence of key and index is according to the object at that hierarchy.
I hope this will be work for you.
NSArray *test = #[#[#1,#2,#3,#4],
#[#3,#5,#6,#7]];
NSLog(#"Test array: %#", test);
NSLog(#"Test firstObject: %#", [test firstObject]);
NSLog(#"Test lastObject : %#", [test lastObject]);
NSLog(#"Test objectAtIndex :%#", [test objectAtIndex:0]);
NSLog(#"Test objectAtIndex 2 :%#", test[0]);
Related
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[jsonArray removeAllObjects];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
responseData = nil;
NSMutableArray *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
NSMutableArray * myArray = [[NSMutableArray alloc] init];
NSMutableDictionary * myDict = [[NSMutableDictionary alloc] init];
if (([(NSString*)sdf isEqual: [NSNull null]])) {
// Showing AlertView Here
}else {
for (int i=0; i<[sdf count]; i++) {
myDict=[sdf objectAtIndex:i];
[myArray addObject:[myDict objectForKey:#"RxnCustomerProfile"]];
}
jsonArray=[myArray mutableCopy];
NSMutableDictionary *dict=[jsonArray objectAtIndex:0];
if ([dict count]>1) {
// Showing AlertView Here
}
}
}
Hi Everyone, I have an issue regarding the -[__NSArrayM objectForKey:]: .
Tried to solve but did not get the better solution for it. Please help me to
find the solution. Thanks In Advance
Below is the issues
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x19731d40'
This is a debugging problem and nobody can really solve it for you as you are using non-local variables whose definition and values are unknown, don't mention that you are using SBJSON (I guess), etc. But let's see if we can give you some pointers. Your error:
[__NSArrayM objectForKey:]: unrecognized selector sent to instance
That tells you that you sent a dictionary method (objectForKey) to an array (__NSArrayM). So somewhere you have an array when you think you have a dictionary.
Now you declare and allocate a dictionary:
NSMutableDictionary * myDict = [[NSMutableDictionary alloc] init];
but then assign to it:
myDict=[sdf objectAtIndex:i];
So this discards the dictionary you allocated and instead assigns whatever is at index i in the array sdf. How do you know, as opposed to think, that the element of the array is a dictionary? You don't test to check...
So where did sdf come from? This line:
NSMutableArray *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
So that calls JSONValue on some unknown string, assumes the result is a dictionary (could it be an array? or a failure?), looks up a key (did your error come from this line?), and assumes the result is an array.
So what you need to do is go and test all those assumptions, and somewhere you'll find an array where you think you have a dictionary.
Happy hunting!
YOU FETCH THE VALUE IN ARRAY FORMAT AND YOU INTEGRATE METHOD IN DICTIONARY.
You do not need to iterate keys and values of dict can directly pass values to array inside else part like:
myArray = [sdf objectForKey:#"RxnCustomerProfile"];
Key RxnCustomerProfile itself containing array not dictionary.
Change your if else part use below code:
if (([(NSString*)sdf isEqual: [NSNull null]])) {
// Showing AlertView Here
}else {
myArray = [sdf objectForKey:#"RxnCustomerProfile"];
}
NSMutableArray *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
Check Sdf
if([sdf isKindOfClass:[NSDictionary class]])
{
NSLog(#"Dictionary");
}
else if([sdf isKindOfClass:[NSArray class]])
{
NSLog(#"NSArray");
}
else if([sdf isKindOfClass:[NSMutableArray class]])
{
NSLog(#"NSMutableArray");
}
First of all it seems like your json is not actually correctly formatted. Without knowing what responseData looks like it's difficult to say exactly what is wrong. But in your code there are a few areas where it can be improved.
First of all you don't need to use [responseString JSONValue]. You can short circuit it entirely with
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSArray *sdf = responseDictionary[#"DataTable"];
Now, the rest all depends on the data in responseData.
But you can make your code a little bit cleaner with (if I understand what you're trying to achieve correctly:
NSMutableArray *myArray = [NSMutableArray array];
if ([sdf isEqual:[NSNull null]]) {
// Showing AlertView here
} else {
for (NSDictionary *myDict in sdf) {
[myArray addObject:dict[#"RxnCustomerProfile"]];
}
}
// No idea what you're trying to achieve here, but here goes:
jsonArray = [myArray mutableCopy];
NSDictionary *dict = jsonArray.first;
if (dict.count > 1) {
// Showing AlertView here
}
Some things to note. You make very liberal use of NSMutableArray and NSMutableDictionary for no apparent reason. Only use mutable if you're actually changing the array or dictionary.
I am working with the following function atm, but I'm banging my head against a wall.
-(double)fetchTimeUntilNextUpdateInSeconds{
NSFetchRequest *fetchReq = [[NSFetchRequest alloc]initWithEntityName:#"DataInfo"];
fetchReq.predicate = [NSPredicate predicateWithFormat:#"data_info_id == 1"];
[fetchReq setPropertiesToFetch:[NSArray arrayWithObject:#"nextupdate"]];
NSArray *array = [self.context executeFetchRequest:fetchReq error:nil];
NSString *string = [[array valueForKey:#"nextupdate"] stringValue];
NSLog(#"string: %# array count:%lu", string, (unsigned long)array.count);
NSArray *hoursAndMins = [string componentsSeparatedByString:#":"];
int hours = [hoursAndMins[0] intValue];
int mins = [hoursAndMins[1] intValue];
return (mins*60)+(hours*60*60);
}
LOG: string: (
"05:42"
) array count:1
I'm getting following error: -[__NSArrayI componentsSeparatedByString:]: unrecognized selector sent to instance 0x174224060'
fair enough, i try to invoke "stringValue" method on string (as showed in code snippet) and get the following instead:
-[__NSArrayI stringValue:]: unrecognized selector sent to instance 0x174224060'
The ladder makes me think I'm already receiving a string as stringValue is not a method of that class.... but why won't the first work then. Better yet, what am I doing wrong here?
I guess, executeFetchRequest returns an array containing always one item.
The mistake is the method valueForKey which is ambiguous. It's a key value coding method as well as a method of NSManagedObject. If you want to get the value of a key of one object, so first get the first object from the array and then call valueForKey.
NSArray *array = [self.context executeFetchRequest:fetchReq error:nil];
// get the value of the key `nextUpdate` of the first item of the array
NSString *string = [array[0] valueForKey:#"nextupdate"];
To make clear what's happening when valueForKey is sent to an array, see this code, it returns an array of the values for the key id of all members of the array.
NSArray *array = #[#{#"name" : #"John", #"id" : #"1"}, #{#"name" : #"Jane", #"id" : #"2"}];
NSLog(#"%#", [array valueForKey:#"id"]); // --> #[#"1", #"2"]
Uhh, could also be the case that ( "05:42" ) has quotation marks that you may need to escape before you write this as a string to an array. OR you just maybe need to typecast the value of string AGAIN, but instead of doing that, why not try this first and tell us what happens.
NSArray *hoursAndMins = [[[array valueForKey:#"nextupdate"] stringValue] componentsSeparatedByString:#":"];
I need to get a count of the objects in array inside of NSDictionary. For example:
po _dictionary
{
keys = (
"one",
"two"
);
}
Taking in consideration this is an array : [_dictionary objectForKey:#"keys"]
my question is how can I get the count in the array?
I try this :
[[[_tutorials objectForKey:#"keys"] allKeys ]count];
but I'm getting this error:
* Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFArray allKeys]:
unrecognized selector sent to instance 0xa419ea0'
[_dictionary objectForKey:#"keys"] is an NSArray and not an NSDictionary. Therefore, it doesn't understand the allKeys method. Drop it and it should work:
[[_dictionary objectForKey:#"keys"] count];
Here you go:
NSLog(#"%lu", _dictionary[#"keys"].count);
NSDictionary has a method to get a NSArray of keys which I find is much more readable than using objectForKey:
[[_dictionary allKeys] count]
NSLog(#"%d", [[_dictionary objectForKey:#"keys"] count]);
As your [_dictionary objectForKey:#"keys"] is an array you can get the count directly.
NSDictionary *res=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];
NSLog(#"%d",[[res valueForKey:#"result"] count]);
We have the following method where we are trying to access an array object at a given index. The array is resultArr. When we do a resultArr count it gives us a result of 13. So we know that the array is not null but when we try to do objectAtIndex it crashes with the error.
Function:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray *keys = [json allKeys];
NSLog(#"keys: %#",keys);
NSArray* htmlAttributions = [json objectForKey:#"html_attributions"]; //2
NSArray* resultArr = (NSArray *)[json objectForKey:#"result"]; //2
NSArray* statusArr = [json objectForKey:#"status"]; //2
NSLog(#"htmlAttributions: %#",htmlAttributions);
NSLog(#"result: %#", resultArr); //3
NSLog(#"status: %#", statusArr); //3
NSLog(#"resultCount: %d",[resultArr count]);
[resultArr objectAtIndex:0];
}
Error:
2012-04-01 22:31:52.757 jsonParsing[5020:f803] resultCount: 13 2012-04-01 22:31:52.759 jsonParsing[5020:f803] -[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6d2f900 2012-04-01 22:31:52.760 jsonParsing[5020:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6d2f900'
*** First throw call stack:
Thank you.
The error message is fairly descriptive. One of the objects that your code expects to be an NSArray is actually an NSDictionary. You cannot access fields inside of an NSDictionary by using NSArray methods (and casting from NSDictionary* to NSArray* will not convert an NSDictionary into an NSArray).
This would mean that inside of the JSON, one of your elements was serialized as an object/associative array instead of as a plain array. You can easily determine which one by looking at your JSON data as text, and finding the item that uses { and } instead of [ and ].
You are saying
NSArray* resultArr = (NSArray *)[json objectForKey:#"result"]; //2
But that does not make this object ([json objectForKey:#"result"]) an NSArray. It is an NSDictionary, and sending it a message that NSDictionary does not respond to (objectAtIndex:) causes a crash.
You were able to send it the count message without crashing because NSDictionary does happen to respond to the count message. But your preconception that this is an array is still mistaken.
You cannot cast an NSDictionary* to an NSArray* as you tried to do with this line: NSArray* resultArr = (NSArray *)[json objectForKey:#"result"];, then call -objectAtIndex.
i have some very strang behavior in iOS when using a NSMutableDictionary.
I am using the following code to access a dictionary from the app delegate.
self.dictTyp = appDelegate.dictTyp;
NSLog(#"%#", dictTyp);
NSArray *keys = [dictTyp allKeys];
The output of the NSLog is fine and it shows the content of the dictionary. but in the next line when i want to get allKeys i get an failure with unrecognized selector. can anybody tell me what i am doing wrong ?
thanks,
martin
Modify NSLog to print out the type, too:
NSLog(#"%# %#", dictTyp, [dictType class]);
Check if dicType isn't a dictionary but something else. Then go back to where you created it and make sure it is actually created as a dictionary and that it is properly retained and not released too early.