unrecognized selector sent to instance when trying to retrieve string value - objective-c

I have a NSMutablearray wich contain NSArrays(each array contain int and String values).
When i try to retrieve and display the data from the first array:
That was ok with the int value, it was displayed correctly.
NSLog(#"%i",[[[lesQuestions objectAtIndex:0] objectAtIndex:0] intValue]);
But when i try to display the String value:
NSLog(#"%#",[[[lesQuestions objectAtIndex:0] objectAtIndex:1] stringValue]);
I got exception:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString stringValue]: unrecognized selector sent to instance
I am definitely sure that the int value is the first item (index 0) and the String value is the second (index 1).
When i log the MutableArray which holds the NSArrays, i got the values correctly, so the problem is on the reference of the item i guess.

The object in your array is already an NSString, so the call to stringValue is unnecessary. NSString doesn't implement a method called stringValue, hence the exception you're seeing. Just do this:
NSLog(#"%#",[[lesQuestions objectAtIndex:0] objectAtIndex:1]);
-intValue is a method implemented by NSNumber, to get an integer primitive out of the NSNumber instance, and your use of intValue is correct assuming the first object in the array is an NSNumber (or an NSString, which also implements -intValue).
All that said, I don't generally think it's a great idea to store instances of different classes in the same array like you're doing. You'd probably be better off using an NSDictionary where each value is stored with a unique key, say #"index" for the number and #"name" for the string.

NSLog respectively the ability of standard objects do display themselfs is more powerful than you may think.
NSLog(#"%#",[[lesQuestions objectAtIndex:0] objectAtIndex:0]);
NSLog(#"%#",[[lesQuestions objectAtIndex:0] objectAtIndex:1]);
You could even find this useful unless you have a really high number of array elements:
NSLog(#"%#",[lesQuestions objectAtIndex:0]);
or
NSLog(#"%#",lesQuestions);
Give it a try!

Related

Error trying to separate an array containing managed object context

Could anyone please tell me why I am getting this error and why this code isn't working?
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSArrayI componentsSeparatedByString:]: unrecognized
selector sent to instance 0x109494750'
This is the code with problems:
NSArray *array = [self.managedObjectContext executeFetchRequest:request error:nil];
NSString *dateString = [array valueForKey:#"dateString"];
NSArray *datesArray = [dateString componentsSeparatedByString:#","];//line with problems
When you call valueForKey: on array the result will be an NSArray containing the result of calling valueForKey: on each of it's elements.
So dateString is not actually a string it's an instance of NSArray, which does not respond to componentsSeparatedByString:. You need to index into the array to get the date you want before calling componentsSeparatedByString: on that
It's an indication that dateString isn't a string. When you call -valueForKey: on an array, it returns an array. Per the docs:
Returns an array containing the results of invoking valueForKey: using key on each of the array's objects.
So you're calling a string method on an array. It's not clear what you're trying to accomplish by calling -valueForKey:. Perhaps you meant -objectAtIndex:?

Convert NSDictionary value (id?) to NSString or NSNumber to compare it

pls help me with my trouble:
I can't compare to value to know successful result was or not.
I fetch json-object as NSDictionaty:
NSDictionary *returnDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
And after that I get value for key: code
[returnDictionary objectForKey:#"code"];
If returning value is equal 1 so that's OK, but problem is that I don't know the type value of key "code". I tried to compare id, NSString, NSNumber but all were fail. What type of object should I compare ?
Did you use the comparison operator (==) to compare your objects?
If so, you didn't compare the values of your objects but their memory addresses.
If the object returned by [returnDictionary objectForKey:#"code"] is of type NSString you should use NSString's isEqualToString:
If it returns a NSNumber instance, you could compare the intValue of that object to 1.
[[returnDictionary objectForKey:#"code"] isEqualToString:#"1"]
or
[[returnDictionary objectForKey:#"code"] intValue] == 1
You can use
[[returnDictionary objectForKey:#"code"] isKindOfClass:[NSString class]]
to check the class of the object pulled from the dictionary.
Hope it helps!
If you expect the output to be an integer, you can call intValue.
[[returnDictionary objectForKey:#"code"] intValue] == 1
Also, you can log the type of the returned object by + class; method.
NSLog(#"%#", [[returnDictionary objectForKey:#"code"] class]);
put in a breakpoint and print out the classname...
type into the debugger: po [[returnDictionary objectForKey:#"code"]className]
that will give you the class, something like _NSCFString will be a string etc...
id is something of a "cheat" in Objective-C, though one that is officially "blessed". Generally, where a method returns id you can directly use that value to invoke a method on the returned type, without having to first cast to the appropriate type -- the compiler knows to suppress "can't find that method name" type warnings/errors when the call is on an id.
Of course, if you don't know the class of the object, you don't know whose methods to call. As Pablo suggests you can use isKindOfClass to test, if you have a suspicion. Alternatively, you can log the class name of an object with NSLog(#"The class is %s", object_getClassName(someId)); or one or two other ways.

How to get string from NSArray which contains bracket

my code is like this:
(here name is NSArray and object is also array which is passed as function parameter)
[name addObject:object];
NSlog(#"%#",name);
When i do this then i got output like this:
{name:\"Malay Basu"\ date:\"2013-04-18"\ senderId:\"24" receiverId:\"25"}
Now when i am retrieving name field of array into string then i got the string as:
NSString *temp = [name valueForKey:#"name"];
output: `( Malay Basu )`
Now when i do string operations like string appending or comparison of string then i got the error like:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:
'-[__NSArrayI isEqualToString:]: unrecognized selector sent to instance 0x16635ed0'
To remove this error i need this string without bracket as displays above. So i need Malay Basu instead of ( Malay Basu ).So what is my next step to fetch proper string into another string variable because i need to do operations like string compare,string appending. Any help will be appreciated.
Check the purpose of the methods you are using.
-valueForKey: when called on an NSArray
Returns an array containing the results of invoking valueForKey: using key on each of the array's objects.
So your object isn't a string, it's an array of strings.
The log statement shows brackets because that is the log notation for NSArray. Similarly {} brackets are the log notation for NSDictionary.
To process the result strings, use a loop.
for (NSString *aString in anArray) {
NSLog(#"%# is an %#", aString, NSStringFromClass([aString class]);
}

nsdictionary issue

I have the following data in a NSDictionary Variable:
{
value = "TV-PG";
}
I was wondering how to get the value for key "value" here.
I tried:
NSDictionary *fieldMaturityRating = [[parsedItems objectAtIndex:0] objectForKey:#"field_maturity_rating"];
NSString *dateRelease = [fieldMaturityRating objectForKey:#"value"];
(where, fieldMaturityRating is a NSDictionary with the given value)
and I get:
-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0xd9cd3f0
[10530:707] *** Terminating app due to uncaught exception: -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0xd9cd3f0
Can anyone kindly help me ?
Thanks.
Note: if I pause the execution and do a po after the 1st line of code presented here, I get the following:
(gdb) po fieldMaturityRatingNew
<__NSArrayM 0x79af250>(
{
value = "TV-PG";
}
)
The po actually shows your issue:
(gdb) po fieldMaturityRatingNew
<__NSArrayM 0x79af250>(
{
value = "TV-PG";
}
)
The outer ( and ) mean that your object is actually an array.
Inside that is where the { and } denote your dictionary.
So you really want:
NSString *value = [[fieldMaturityRatingNew objectAtIndex:0] objectForKey:#"value"];
You're actually sending that NSDictionary message to a NSMutableArray instance.
You might want to check your code again as the objectForKey: method is right when pointing to a NSDictionary.
This means your fieldMaturityRating is not actually an NSDictionary. Make sure you aren't setting it to an array somewhere in your code.
Edit:
This means your fieldMaturityRating is actually an NSArray containing an NSDictionary. If this is your intended data structure then you can access your value like so.
NSString *dateRelease = [[fieldMaturityRating objectAtIndex:0] objectForKey:#"value"];
I don't believe this is your intended data structure so you should look into why your parsedItems array returned you an NSArray instead of an NSDictionary. If you track this problem down you can stop any headaches in the future.
Based on your datastructure which is a dictionary inside an array, dateRelease should be like this
NSString *dateRelease = fieldMaturityRating[0][#"value"];

Terminating the app due to uncaught exception in Objective-C for iPhone app

i've written a for loop in Objective-C, This is how my code looks like
NSString *string = [NSString stringWithContentsOfFile=#"/Users/Home/myFile.doc"];
NSString *seperator=#"\n";
NSArray *mainarray = [string componentsSeparatedByString:seperator];
// Since i want to parse each element of mainarray
for(NSString *s in mainarray)
{
//again parising the string using a new separator
NSString newseparator = #"=";
NSArray *subarray = [s componentsSeparatedByString : newseparator];
//Copying the elements of array into key and object string variables
NSString *key = [subarray objectAtIndex:0];
NSLog(#"%#",key);
NSString *class_name= [subarray objectAtIndex:1];
NSLog(#"%#",class_name);
// create an instance for the class_name
//dont knw how it ll take the value from file and ???
//Putting the key and objects values into hashtable
NSMutableDictionary = [NSDictionary dictinaryWithObject:class_name forKey:key];
}
Whenever i execute this code this crashes my program saying as, Terminating the app due to uncaught exception NSRangeException
How to know the range of array and how to specify the terminating condition in the for loop???and plz let me knw how to handle this exception???
I'm surprised that code even compiles. If I remember correctly, it can't compile unless you have gone to great lengths to turn off a whole bunch of compiler warnings.
NSString newseparator = #";";
That should give an error write there in that you don't have the *.
NSString *key = [subarray objectAtIndex[0]];
NSString *object = [subarray objectAtIndex[1]];
Neither of these lines of code make any sense.
It would appear that you haven't posted the actual code?
Now, getting back to the exception. A range exception will be tossed if you try to access an item at an index that is outside of the range of indexes available in the array. Thus, if componentsSeparatedByString: returned an array of 0 or 1 elements, then [subarray objectAtIndex: 1]; will cause a range exception to be raised.
What you don't want to do is to try and handle the exception using an #catch block. In Cocoa (and iPhone development), exceptions are treated as non-recoverable errors.
So, instead, use the -count method on NSArray to verify that the array actually contains the # of elements you were expecting. Since you are writing a casual parser, this is probably a good idea as a minimal check of input validity.