I am receiving error:
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFConstantString
subjectType]: unrecognized selector sent to instance
I am trying to sort students in my app to arrays by the subject type that they are learning.
AMStudent* student = [[AMStudent alloc] init];
NSMutableArray* studentArray = [[NSMutableArray alloc] init];
NSArray* studentNameArray = [NSArray arrayWithObjects: #"Student1", #"Student2", #"Student3", #"Student4", #"Student5", #"Student6", #"Student7", #"Student8", #"Student9", #"Student10", nil];
[studentArray addObjectsFromArray:studentNameArray];
for (NSInteger i = 0; i < [studentNameArray count]; i++) {
student.name = [studentNameArray objectAtIndex: i];
[student randomAnswer];
NSLog(#"%#", student.description);
}
NSMutableArray* techArray = [NSMutableArray array];
NSMutableArray* humArray = [NSMutableArray array];
for (AMStudent* stud in studentArray){
if ((stud.subjectType & AMStudentSubjectTypeDevelopment) | (stud.subjectType & AMStudentSubjectTypeMath)) {
[techArray addObject:stud];
} else {
[humArray addObject:stud];
}
}
I cant figure out what exactly I am doing wrong, because it crashes in this stage:
if ((stud.subjectType & AMStudentSubjectTypeDevelopment) | (stud.subjectType & AMStudentSubjectTypeMath)) {
[techArray addObject:stud];
} else {
[humArray addObject:stud];
}
You are calling
stud.subjectType
in the studentArray after copying the studentNames (NSString) to the student array:
[studentArray addObjectsFromArray:studentNameArray];
NSString won't recognize subjectType.
You fill studentArray using:
[studentArray addObjectsFromArray:studentNameArray];
So studentArray contains NSString instances. You then attempt to process the array using:
for (AMStudent* stud in studentArray){
This does not magically convert the NSString instances in studentArray into AMStudent instances. You don't get an error at this point as studentArray can contain objects of any type so the compiler just trusts you know what you are doing and places a reference to an NSString into stud. You then do:
if ((stud.subjectType ...
and this requires stud to reference an AMStudent object, which it does not, it references a (constant) string and so you get the error:
NSInvalidArgumentException', reason: '-[__NSCFConstantString subjectType]: unrecognized selector sent to instance
Instead of copying the names of the students into studentArray you need to create instances of AMStudent and add those to the array. Did you intend to do that in the first loop maybe?
HTH
techArray and humArray (NSArray) type change not working add object function.
NSMutableArray *newtechArray = [techArray mutableCopy];
NSMutableArray *newhumArray = [humarray mutableCopy];
if ((stud.subjectType & AMStudentSubjectTypeDevelopment) | (stud.subjectType & AMStudentSubjectTypeMath)) {
[newtechArray addObject:stud];
} else {
[newhumArray addObject:stud];
}
Thanks a lot for Your wide answer, I understood my mistake. Just added one more loop and added object student.
for (NSInteger numberOfStudents = 0; numberOfStudents < 10; numberOfStudents ++){
AMStudent* student = [[AMStudent alloc] init];
student.name = [studentNameArray objectAtIndex:numberOfStudents];
}
[studentArray addObject:student];
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've looked at lots of questions about NS(Mutable)Arrays. I guess I am not grokking the concept, or the questions don't seem relevant.
What I' trying to do is the following:
Incoming Array 1:
Name
Code
Start time
End Time
etc
Incoming Array 2
Code
Ordinal
What I want:
Ordinal
Name
Code
Start time
End Time
etc
This is my code at present:
int i=0;
for (i=0; i < stationListArray.count; i++) {
NSString *slCodeString = [stationListArray[i] valueForKey:#"Code"];
NSLog(#"slCodeString: %#", slCodeString);
int j=0;
for (j=0; j< lineSequenceArray.count; j++) {
NSString *lsCodeString = [lineSequenceArray[j]valueForKey:#"StationCode"];
NSLog(#"lsCodeString: %#", lsCodeString);
if ([slCodeString isEqualToString:lsCodeString]) {
NSLog(#"match");
NSString *ordinalString = [lineSequenceArray[j] valueForKey:#"SeqNum"];
NSLog(#"ordinalString: %#", ordinalString);
[stationListArray[i] addObject:ordinalString]; <------
}
}
}
I'm logging the values and they return correctly.
The compiler doesn't like the last statement. I get this error:
[__NSCFDictionary addObject:]: unrecognized selector sent to instance 0x7f9f63e13c30
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary addObject:]: unrecognized selector sent to instance 0x7f9f63e13c30'
Here is an excerpt from the StationListArray:
(
{
Address = {
City = Greenbelt;
State = MD;
Street = ".....";
Zip = 20740;
};
Code = E10;
Lat = "39.0111458605";
Lon = "-76.9110575731";
Name = Greenbelt;
}
)
NSString *ordinalString = [lineSequenceArray[j] valueForKey:#"SeqNum"]; //Is NSString
[stationListArray[i] addObject:ordinalString];//<----- trying to call addObject method of NSMutableArray on NSDictionary -> Not GOOD
When you do [stationListArray[i] you get NSDictionary in your case
(Generally it returns an NSObject that is inside the NSArray at the given index, in your case is NSDictionary).
So in order to complete your desired operation: you should make an NSMutableDictionary instance (In this case it should be the mutableCopy from the stationListArray[i]'s NSObject which is NSDictionary, when you do mutableCopy it copies the entire NSDictionary and makes it Mutable)
make the changes on it and then assign it in to the stationListArray[i]
For example:
NSMutableDictionary * tempDict = [[stationArray objectAtIndex:i]mutableCopy];//Create a mutable copy of the `NSDictionary` that is inside the `NSArray`
[[tempDict setObject:ordinalString forKey:#"Ordinal"]; //In this line you are adding the Ordinal `NSString` in to the tempDict `NSMutableDictionary` so now you have the desired `NSMutableDictionary`. You can change the key to whatever you wish.
[stationArray replaceObjectAtIndex:i withObject:[tempDict copy]];//Swap the original(old NSDictionary) with the new updated `NSMutableDictionary` I used the copy method in order to replace it with the IMMUTABLE `NSDictionary`
[stationListArray[i] addObject:ordinalString]; <------
This is not an NSMutableArray. You must use
[stationListArray addObject:ordinalString]; <------
instead of the what you have done.
Here is the way you can write a better understandable code because for me the code is not clear.You can also try like this in loop to achieve what you want.
NSMutableArray *array = [NSMutableArray new];
NSMutableDictionary *dictMain = [NSMutableDictionary new];
NSMutableDictionary *dictAddress = [NSMutableDictionary new];
[dictAddress setValue:#"Greenbelt" forKey:#"City"];
[dictAddress setValue:#"MD" forKey:#"State"];
[dictAddress setValue:#"....." forKey:#"Street"];
[dictAddress setValue:#"20740" forKey:#"Zip"];
[dictMain setValue:dictAddress forKey:#"Address"];
[dictMain setValue:#"E10" forKey:#"Code"];
[dictMain setValue:#"39.0111458605" forKey:#"Lat"];
[dictMain setValue:#"-76.9110575731" forKey:#"Lon"];
[dictMain setValue:#"Greenbelt" forKey:#"Name"];
[array addObject:dictMain];
following snippet gives me :
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '- [__NSCFString count]: unrecognized selector sent to instance 0x8ce0c00'
-(void)loadInfo{
// Create the query.
NSString *query = [NSString stringWithFormat:#"select * from tableName where category=\"%#\" ", #"cat1"];
// Load the relevant data.
NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
NSMutableArray *List = [[NSMutableArray alloc]init];
NSLog(#"Count..:%d",results.count);
for(int i=0; i<results.count; i++){
List = [[results objectAtIndex:i] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"itemName"]];
}
NSLog(#"Result..:::: %d", [List count]);
}
What is going wrong here? Cant i print List count? dbmanager is what I have implemented using eg. given in - http://www.appcoda.com/sqlite-database-ios-app-tutorial/
This operation replaces List on every loop iteration with a different object:
List = [[results objectAtIndex:i] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"itemName"]];
Judging from the error, the object happens to be NSString.
What you probably wanted is to add objects to your mutable array List:
[List addObject:[[results objectAtIndex:i] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"itemName"]]];
Hello guys I am new to Xcode/iOS developing
I trying to add json data to the mutable array , and it results in app crash :(
so far here is my code:
if(! [defaults objectForKey:#"Person1"])
[defaults setObject:[PersonsFromSearch objectAtIndex:index] forKey:#"Person1"];
else
{
NSMutableArray *Array = [[NSMutableArray alloc]init];
id object = [defaults objectForKey:#"Person1"];
Array = [object isKindOfClass:[NSArray class]] ? object : #[object];
[Array addObject:[PersonsFromSearch objectAtIndex:index]];//crash here :((
[Array moveObjectFromIndex:[Array count] toIndex:0];
}
Crash Dump:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI addObject:]: unrecognized selector sent to instance 0xcb4d380'
* First throw call stack:
what is wrong here ? can you please help me to resolve this issue
Array contains this (Json?)
{
Address = "\U05d3\U05e8\U05da \U05d4\U05e9\U05dc\U05d5\U05dd 53";
CellPhone = "052-3275381";
EMail = "editor#pc.co.il";
EnglishPerson = "Yehuda Konfortes";
FaceBookLink = "";
Fax1 = "03-7330703";
Fax2 = "";
FileNAme = "100050.jpg";
HomeEMail = "";
HomeFax = "";
HomePhone1 = "";
HomePhone2 = "";
PersonID = 100050;
PersonName = "\U05d9\U05d4\U05d5\U05d3\U05d4 \U05e7\U05d5\U05e0\U05e4\U05d5\U05e8\U05d8\U05e1";
Phone1 = "03-7330733";
Phone2 = "";
ZipCode = "";
}
[defaults objectForKey:#"Person1"]; returns dictionary but not array.
So you can't use addObject method.
UPD
You may resolve this crash by creation array with a single object.
Here is updated code:
NSMutableArray *Array = [[NSMutableArray alloc]init];
id object = [defaults objectForKey:#"Person1"];
Array = [object isKindOfClass:[NSArray class]] ? [object mutableCopy] : [#[object] mutableCopy];
[Array addObject:[PersonsFromSearch objectAtIndex:index]];//crash here :((
[Array moveObjectFromIndex:[Array count] toIndex:0];
NSMutableArray *_arr = [[NSMutableArray alloc]init];
NSDictionary *results = PASS JSON Value;
[_arr add object:[results objectforkey:#“Address”]];
[_arr add object:[results objectforkey:#“CellPhone”]];
I initialize this NSMutableDictionary:
define TAREFA #"TAREFA"
define DATA_ITEM #"DATA"
define HORA_ITEM #"HORAS"
define ID #"ID"
define STATE #"NA"
define APROVED #"APROVED"
define REJECTED #"REJECTED"
itensArray = [[NSMutableArray alloc] init];
for (int i=0; i< [listagens size]; i++)
{
NSMutableDictionary *tmpDictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
[[listagens item:i] WI_ID], ID,
[[listagens item:i] WI_TEXT], TAREFA,
[[listagens item:i] WI_CD], DATA_ITEM,
[[listagens item:i] WI_CT], HORA_ITEM,
STATE, STATE,
nil];
[itensArray addObject:tmpDictionary];
}
Later on, i do the following:
for (int i=0; i<[itensArray count]; i++)
{
if ([[[itensArray objectAtIndex:i] objectForKey:ID] isEqualToString:cell.idLabel.text]) {
[[itensArray objectAtIndex:i] setString:APROVED forKey:STATE];
break;
}
}
I initialize the array, then later on, i change a string of the NSMutableDictionary. When i set the value i get the following runtime error:
'NSInvalidArgumentException', reason: '-[__NSCFDictionary
setString:forKey:]: unrecognized selector sent to instance 0x7b7d170'
It appears i´m not changing the value correctly. Is it a syntax error? How is it done?
maybe you misspelled the name of the method.
// WRONG
[[itensArray objectAtIndex:i] setString:APROVED forKey:STATE];
// GOOD
[[itensArray objectAtIndex:i] setValue:APROVED forKey:STATE];
'NSInvalidArgumentException', reason: '-[__NSCFDictionary setString:forKey:]: unrecognized selector sent to instance 0x7b7d170'
NSMutableDictionary has no setString:forKey: method.
Try setObject:forKey:
[[itensArray objectAtIndex:i] setObject:APROVED forKey:STATE];