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”]];
Related
I am getting crash when i am replacing the value in NSMutableArray and the message is
"Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: '-[__NSCFDictionary
setObject:forKey:]: mutating method sent to immutable object'"
What I am doing is first store an array in NSUserDefaults and then get the array . After that i am editing the copy of that array .
NSMutableArray *getArr = [[NSUserDefaults standardUserDefaults] valueForKey:#"List"];
NSMutableArray *newArray = [[NSMutableArray alloc]initWithArray:getArr copyItems:YES];
And Now I am replacing the value of new Array at particular index
for(int i = 0;i<newArray.count;i++)
{
NSDictionary *dict = [newArray objectAtIndex:i];
dict["key"] = "NewValue"
[newArray replaceObjectAtIndex:i withObject:d];
}
The problem is that the stored dictionary object is immutable , so you need to init a mutable one with it's content , do the job then save it again see this example
NSMutableArray*old= [NSMutableArray new];
[old addObject:#{#"key":#"value"}];
[[NSUserDefaults standardUserDefaults] setObject:old forKey:#"www"];
NSMutableArray*edited = [[[NSUserDefaults standardUserDefaults] objectForKey:#"www"] mutableCopy];
NSMutableDictionary*dic = [[NSMutableDictionary alloc] initWithDictionary:[edited objectAtIndex:0]];
dic[#"key"] = #"value2";
[edited replaceObjectAtIndex:0 withObject:dic];
[[NSUserDefaults standardUserDefaults] setObject:edited forKey:#"www"];
NSMutableArray*vvv = [[NSUserDefaults standardUserDefaults] objectForKey:#"www"];
NSLog(#"%#",vvv); /// key:value2
The problem is that you have only array copied as mutable. But dictionaries inside are still immutable objects. You can try making a deep mutable copy but for your case you can just do the following
for(int i = 0;i<newArray.count;i++)
{
//Just copy the dict as mutable and then change the value
NSDictionary *dict = [[newArray objectAtIndex:i] mutableCopy];
dict["key"] = "NewValue"
[newArray replaceObjectAtIndex:i withObject:dict];
}
- (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 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];
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];
I have this code:
NSDictionary *jsonGuardado = [self dictionaryFromJson:JSON];
NSLog(#"HOLA %#",jsonGuardado);
NSMutableArray *arrayCodigos = [jsonGuardado objectForKey:#"code"];
codigos = arrayCodigos;
(Codigos is an NSMutableArray)
The NSLOG return this:
HOLA (
{
code = 22051310;
},
{
code = 22051311;
},
{
code = 22051312;
},
{
code = 22051313;
}
)
But right after this, a message error says:
-[JKArray objectForKey:]: unrecognized selector sent to instance
I search this error in Google and here and all the questions I found not help me.
I'm using the JSONKit for make the dictionaryFromJson method.
You try this,
NSArray *jsonGuardado = [self dictionaryFromJson:JSON];
NSLog(#"HOLA %#",jsonGuardado);
NSMutableArray *arrayCodigos = [NSMutableArray arrayWithArray:[jsonGuardado valueForKey:#"code"]];
NSLog(#"arrayCodigos %#", arrayCodigos);
It will print only values.
The parser returns an array and not a dictionary in your case.
[self dictionaryFromJson:JSON] returns a Json array but you are capturing it in NSDictionary
Your log says that it's already NSArray. You should try below
NSMutableArray *jsonGuardado = [NSMutableArray array];
jsonGuardado = (id)[self dictionaryFromJson:JSON];
NSLog(#"HOLA %#",jsonGuardado);
NSMutableArray *arrayCodigos = [[jsonGuardado objectAtIndex:0] valueForKey:#"code"];
codigos = [arrayCodigos copy];
NSLog(#"Array %#",codigos);