trouble retrieving string from array - ios

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:#":"];

Related

NSDictionary values changes without any modification

I added an NSDictionary to NSMutableArray.
for (TblFiles *objTblFile in visitorFilesArray) {
NSData *fileDataTemp = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: objTblFile.internalFileName]];
NSDictionary *tempDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:(NSInteger)objTblFile.fileID],#"fileID",
objTblFile.fileName,#"fileName",
fileDataTemp,#"fileData",nil];
[filesArrayInAddVisitor addObject:tempDict];
}
After that I tried to delete one dictionary from this array, I am getting crash. It happens because of fileID values are changed. Some time its working perfect. Some times getting crash.
NSPredicate *objPredicate = [NSPredicate predicateWithFormat:#"fileID == %#",151];
NSArray *filterArray = [filesArrayInAddVisitor filteredArrayUsingPredicate:objPredicate];
[self->filesArrayInAddVisitor removeObject:[filterArray objectAtIndex:0]];
[self->fileTableView reloadData];
I don't know why values are changed in NSDictionary.
Example : I added fileID as 151, but in NSMutableArray it changed to zero in some cases.
1.First problem i got for crash is the predicate string.
replace it with this
NSPredicate *objPredicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"fileID == %d",151]];
2.You are saying that fileID value got change then first confirm that what is the type of objTblFile.fileID if it is NSInteger then its ok.
For my example i have passed NSInteger there and code working fine.

NSLog nsarray in nsarray

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]);

-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x9d0d720

- (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.

How to add an index to an NSMutableArray based on value in another array?

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];

get single FetchedObject from FCR to write Label

I have a problem with my FCR. I want to show my datas on Labels but FCR doesnt allow me.There is my codes..
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"faturaAdi == 'ADSL' "];
I have fetched only 1 data which fatura name is ADSL.. and I want to write this faturaAdi on my label but i couldn't do that.
NSArray *array = [[NSArray alloc]init];
array = self.fetchedResultsController.fetchedObjects;
_lblFaturaAdi.text = [self.fetchedResultsController.fetchedObjects valueForKey:#"faturaAdi"];
NSLog(#"%#",[array valueForKey:#"faturaAdi"]);
NSLog shows Takip[967:60b] (
ADSL
)
When i put the
_lblFaturaAdi.text = [self.fetchedResultsController.fetchedObjects valueForKey:#"faturaAdi"];
app crash with this error ;
-[__NSArrayI length]: unrecognized selector sent to instance 0xa18c740
how can i solve this ?
Your code should change to:
NSArray *array = self.fetchedResultsController.fetchedObjects;
if (array.count > 0) {
self.lblFaturaAdi.text = [[array objectAtIndex:0] valueForKey:#"faturaAdi"];
NSLog(#"%#", _lblFaturaAdi.text);
} else {
NSLog(#"no results found");
}
Because you don't need to initialise an array before replacing it and you need to index into the array before you can extract the value.

Resources