objectForKey: returning null - ios

Hi people I m working on a AlarmApp and I want to schedule some localNotifications, this works so far, but when I try to delete them my problem appears. I'm trying to list all localNotifications and loop throughout their userInfo to determinate which Notification has to be deleted. I've added a dictionary to the userInfo property of the Notification with value = index of alarm im alarmArray and key = "index" and now I'm trying to get backt that index with objectForKey: I've also tried valueForKey: but it doesn't work. When I log the dictionary it said that the dictionary contains one item: { 0 = index; } but when I try to log the valueForKey:#"index" the console gives me back a "null".
So can someone tell me what I'm doing wrong? Here's my code:
- (void)deleteNotificationForKey:(int)key
{
UIApplication *application = [UIApplication sharedApplication];
NSArray *eventArray = [application scheduledLocalNotifications];
for (int i = 0; i < eventArray.count; i++) {
UILocalNotification* notification = [eventArray objectAtIndex:i];
NSDictionary *currentUserInfo = notification.userInfo;
NSString *index = [currentUserInfo objectForKey:#"index"];
NSLog(#"%s:%#",__PRETTY_FUNCTION__,currentUserInfo);
NSLog(#"%s:%#",__PRETTY_FUNCTION__,index);
NSLog(#"%s:%d",__PRETTY_FUNCTION__,key);
if ([index intValue] == key)
{
NSLog(#"%s:%#",__PRETTY_FUNCTION__,notification);
[application cancelLocalNotification:notification];
}
}
}

It should work if you use stringWithFormat:
NSString *index = [NSString stringWithFormat:#"%#", [currentUserInfo valueForKey:#"index"]];

In this situation your dictionary object is #"index" and key is #0, if you try this, it should work
NSString *index = [currentUserInfo objectForKey:#0];
To solve this problem you need to change #0 and #"index" places when you initialize your dictionary

Related

Unable to retrieve the data from Dictionary

In my project I am getting response from the server in the form
response:
<JKArray 0x7fa2e09036b0>(
{
id = 23;
name = "Name1";
},
{
id = 24;
name = "Name2";
}
)
From this response array i am retrieving the objects at different indexes and then adding them in a mutableArray and then into a contactsDictionary.
self.contactsDictionary = [[NSMutableDictionary alloc] init];
for(int i=0 ; i < [response count] ; i++)
{
NSMutableArray *mutableArray=[[NSMutableArray alloc] init];
[mutableArray addObject:[response objectAtIndex:i]];
[self.contactsDictionary setObject:mutableArray forKey:[NSString stringWithFormat:#"%i",i]];
}
I want to retrieve data for Key #"name" from the contactsDictionary at some other location in the project. So how to do it.
Thanks in advance....
this is the wrong way like you are setting your contactsDictionary.
replace below line
[self.contactsDictionary setObject:mutableArray forKey:[NSString stringWithFormat:#"%i",i]];
with
[self.contactsDictionary setObject:[mutableArray objectAtIndex :i] forKey:[NSString stringWithFormat:#"%i",i]];
becuase everytime your array have new objects so your contacts dictionary's first value have one object then second value have two object. so you shouldn't do that.
now, if you want to retrieve name then call like
NSString *name = [[self.contactsDictionary objectForKey : #"1"]valueForKey : #"name"];
avoid syntax mistake if any because have typed ans here.
Update as per comment:
just take one mutablearray for exa,
NSMutableArray *arr = [[NSMutableArray alloc]init];
[arr addObject : name]; //add name string like this
hope this will help :)
Aloha from your respond I can give you answer Belo like that according to you response.
for(int i=0;i<[arrRes count];i++);
{
NSString *strId = [NSString stringWithFormat:#"%#",[[arrRes obectAtIndex:i]objectForKey:#"id"]];
NSString *StrName = [NSString stringWithFormat:#"%#",[[arrRes objectAtIndex:i]objectForKey:#"name"]];
NSLog(#"The ID is -%#",strId);
NSLog(#"The NAME is - %#",strName);
}

Adding a value and key into an NSMutableArray - Objc

I've read and tried a dozen or more variants of my own question, but still need some help please.
I have a large existing array, and I want to add a new object (key and value) to each record.
This is an element in the incoming array:
{
"trip_id": 65,
"arrival_time": "08:56:08",
"departure_time": "08:56:08",
"stop_id": 1161,
"stop_sequence": 8,
"stop_headsign": 0
},
This is what I want to achieve:
{
"trip_id": 65,
"arrival_time": "08:56:08",
"departure_time": "08:56:08",
"stop_id": 1161,
"stop_name": "a stop name",
"stop_sequence": 8,
"stop_headsign": 0
},
This is my code so far -- the commented lines are other attempts:
NSString *nameKey = #"stop_name";
int i=0;
for (i=0; i<stopTimesArray.count; i++) {
NSNumber *stopTimesId = [stopTimesArray[i] valueForKey:#"stop_id"];
int j=0;
for (j=0; j<stopArray.count; j++) {
NSNumber *stopId = [stopArray[j] valueForKey:#"stop_id"];
if (stopId == stopTimesId) {
NSString *stopNameString = [stopArray[j] valueForKey:#"stop_name"];
NSLog(#"stopNameString: %#", stopNameString);
[outgoingStopTimesDictionary setObject:stopNameString forKey:#"stop_name"];
//[outgoingStopTimesArray addObject:outgoingStopTimesDictionary];
//[outgoingStopTimesArray addObjectsFromArray:stopTimesArray[i]];
//[stopTimesArray[i] addObject:#{#"stop_name":stopNameString}];
//[stopTimesArray[i] addObject:#{#"stop_name":stopNameString}];
[stopTimesArray[i] addObject: outgoingStopTimesDictionary];
}
}
}
//NSLog(#"outgoingStopTimesArray: %#", outgoingStopTimesArray);
//NSLog(#"outgoingStopTimesDictionary: %#", outgoingStopTimesDictionary);
//NSLog(#"stopTimesArray: %#", stopTimesArray);
The error I am getting with approach is:
stopNameString: S Monroe Street, NB # 18th Street S, NS
[__NSCFDictionary addObject:]: unrecognized selector sent to instance 0x7fd7f2c22760
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary addObject:]: unrecognized selector sent to instance 0x7fd7f2c22760'
I'm either getting a null dictionary, or an unrecognised object exception when I try to add the dictionary to my array. Please point me to a working answer, and I'll delete my question.
It appears that your goal is to add one new key/value pair to the dictionary at stopTimesArray[i]. Here's your code all cleaned up with what I believe you need:
for (NSMutableDictionary *stopTimesDictionary in stopTimesArray) {
NSNumber *stopTimesId = stopTimesDictionary[#"stop_id"];
for (NSDictionary *stopDictionary in stopArray) {
NSNumber *stopId = stopDictionary[#"stop_id"];
if ([stopTimesId isEqual:stopId]) {
NSString *stopNameString = stopDictionary[#"stop_name"];
stopTimesDictionary[#"stop_name"] = stopNameString;
// Uncomment the following line if "stop_id" is unique within the "stopArray"
// break;
}
}
}
Since it seems your stopTimesArray contains immutable dictionaries, the above code won't work as written. Here is a solution that deals with that:
for (NSInteger i = 0; i < stopTimesArray.count; i++) {
NSDictionary *stopTimeDictionary = stopTimesArray[i];
NSNumber *stopTimesId = stopTimesDictionary[#"stop_id"];
for (NSDictionary *stopDictionary in stopArray) {
NSNumber *stopId = stopDictionary[#"stop_id"];
if ([stopTimesId isEqual:stopId]) {
NSString *stopNameString = stopDictionary[#"stop_name"];
NSMutableDictionary *tempDict = [stopTimesDictionary mutableCopy];
tempDict[#"stop_name"] = stopNameString;
[stopTimesArray replaceObjectAtIndex:i withObject:tempDict];
// Uncomment the following line if "stop_id" is unique within the "stopArray"
// break;
}
}
}
dictTo=[NSDictionary new];
dictTo =
#{
#"vPLocationLat" : [NSString stringWithFormat:#"%#",[[[[json valueForKey:#"result"] valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lat"]],
#"vPLocationLong" : [NSString stringWithFormat:#"%#",[[[[json valueForKey:#"result"] valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lng"]]
};
arrLocationList =[NSMutableArray new];
arrLocationList =[dictTo[#"data"] mutableCopy];
another Solution
-> Try to implement your Code as per in given Code
NSMutableArray* newArray = [NSMutableArray array];
NSArray* oldArray = outerDictionary[#"scores"];
for (NSDictionary* dictEntry in oldArray) {
NSString* leagueCode = dictEntry[#"league_code"];
if ([leagueCode isEqualToString #"epl"]) {
[newArray addObject:dictEntry];
}
}
Another one Solution
Try something like this.
Assume your array is called array and yourNewNameString is your new value for name
for(NSMutableDictionary *dict in array){
if([[dict objectForKey:#"id"]integerValue]==5){
[dict setObject:yourNewNameString forKey#"name"];
}
}
edit This is assuming you initialized your array with NSMutableDictionarys (Not just NSDictionarys)
//You can create dictionary and add it into NSMutableArray Object Like..
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSDictionary *inventory = #{
#"Mercedes-Benz SLK250" : [NSNumber numberWithInt:13],
#"Mercedes-Benz E350" : [NSNumber numberWithInt:22],
#"BMW M3 Coupe" : [NSNumber numberWithInt:19],
#"BMW X6" : [NSNumber numberWithInt:16],
};
[arr addObject:inventory];
//You can access using key like...
NSString *strForBMWX6 = [[arr objectAtIndex:0] valueForKey:#"BMW X6"];
// in your case you just miss objectAtIndex:j
First, thanks #rmaddy.
I modified his answer a bit, but his was basically correct.
My final code looks like this:
for (NSInteger i = 0; i < stopTimesArray.count; i++) {
NSDictionary *stopTimesDictionary = stopTimesArray[i];
NSNumber *stopTimesId = stopTimesDictionary[#"stop_id"];
for (NSDictionary *stopDictionary in stopArray) {
NSNumber *stopId = stopDictionary[#"stop_id"];
if ([stopTimesId isEqual:stopId]) {
NSString *stopNameString = stopDictionary[#"stop_name"];
NSMutableDictionary *tempDict = [stopTimesDictionary mutableCopy];
tempDict[#"stop_name"] = stopNameString;
[outgoingStopTimesArray addObject:tempDict];
break;
}
}
}

UILocalNotification triggered but not scheduled

Hi people I have a problem with my app, where I want to add some basic LocalNotifications, which repeat themselves every week. I want to do this in a method called "scheduleLocalNotificationForItem:", which is called when the doneBarButtonItem is pressed. This all seems to be working so far, because when I log all the scheduled notifications every scheduled notification shows up. But when I use the app, the scheduled notifications get triggered and show up but there are some additional notifications, which I haven't set myself and I can't determinate where they come from, which appear too.
So here's my code:
- (int)scheduleNotifitactionsForItem:(AlarmItem *)item
{
NSArray *reorderdRepeat = [NSArray arrayWithArray:[self transformArray:item.repeat]];
int missedDays = 0;
int scheduledAlarms = 0;
for (int i = 0; i < item.repeat.count; i++) {
if ([[reorderdRepeat objectAtIndex:i] boolValue] == true) {//Problem determinating true values at end of array
NSInteger integerOfDay = i + 1;//reorderRepeat should contain seven items, icrement i bevore adding it to integerOfDay
NSDate *lastAlarmTime = [self getFireDateForDayOfWeek:integerOfDay withTime:item.time];
NSArray *allAlramTimesForDay = [self getFireDatesForTime:lastAlarmTime andCycle:item.cycles];
for (int i = 0; i < allAlramTimesForDay.count; i++) {
NSDate *alarmTime = [allAlramTimesForDay objectAtIndex:i];
UIApplication *application = [UIApplication sharedApplication];
UILocalNotification *notification = [UILocalNotification new];
NSDictionary *userInfo = #{#"index":[NSString stringWithFormat:#"%d",item.notification]};
notification.repeatInterval = NSCalendarUnitWeekday;
notification.alertBody = item.title;
notification.userInfo = userInfo;
notification.fireDate = alarmTime;
notification.soundName = item.sound;
[application scheduleLocalNotification:notification];
scheduledAlarms += 1;
}
} else {
missedDays += 1;
}
}
return scheduledAlarms;
}
Help is appreciated ;)
Your repeatInterval should be NSCalendarUnitWeekOfYear (or old NSWeekCalendarUnit). NSCalendarUnitWeekday (NSWeekdayCalendarUnit) will repeat everyday.

TouchXML CXMLNode.m unrecognized selector when adding to NSMutableArray

I'm new to Objective C and XML, so this is going to look pretty rough.
My code is as follows:
#import "dbCommunicator.h"
#import "BookInfo.h"
#import "TouchXML.h"
#implementation dbCommunicator
-(void)getNextBooks {
if(self.bookListing == nil) {
for(int i = 0; i < 5; i++) {
BookInfo *newBook = [[BookInfo alloc] init];
[self.bookListing addObject:newBook];
}
self.currentPage = 0;
}
if(self.currentPage == 10) {
self.currentPage = 0;
}
NSString *test = #"<Authors><Book.Author><Id>1026</Id><Name>Mark Twain</Name></Book.Author></Authors>";
NSString *bookQueryString = [NSString stringWithFormat:#"http://bookworm.azurewebsites.net/api/book/list/5/%d",_currentPage];
NSURL *bookQueryURL = [NSURL URLWithString: bookQueryString];
self.currentPage++;
NSError *theError = NULL;
NSDictionary *mappings = [NSDictionary dictionaryWithObjectsAndKeys:
#"http://schemas.datacontract.org/2004/07/Bookworm.Models.ResponseModels",
#"datacontract",
nil];
CXMLDocument *xmlReturn = [[CXMLDocument alloc] initWithXMLString:test options:0 error:&theError];
NSArray *returnedBooks = [xmlReturn nodesForXPath:#"//Authors" error:&theError];
for(CXMLElement *resultElement in returnedBooks) {
NSLog(#"%s", "We actually got here");
}
}
There's a lot of junk code in there at the moment. The intention is to pull an XML file from a database and put its information into an array of BookInfo classes. For the moment, I simplified by just using a test XMLstring to ensure it wasn't an issue with what the database was sending me. This makes the dictionary (to deal with the namespace issues TouchXML has) superfluous. Anyways.
It always crashes with a unrecognized selector error on this line:
[theArray addObject:[CXMLNode nodeWithLibXMLNode:theNode freeOnDealloc:NO]];
In this context:
if (xmlXPathNodeSetIsEmpty(theXPathObject->nodesetval))
theResult = [NSArray array]; // TODO better to return NULL?
else {
NSMutableArray *theArray = [NSMutableArray array];
int N;
for (N = 0; N < theXPathObject->nodesetval->nodeNr; N++) {
xmlNodePtr theNode = theXPathObject->nodesetval->nodeTab[N];
[theArray addObject:[CXMLNode nodeWithLibXMLNode:theNode freeOnDealloc:NO]];
}
}
and with that, I'm totally at a loss. I've tried plenty of things, scoured every StackOverflow post even closely related and tried their fixes, nothing's working. Any suggestions?
array is a static method on NSArray a super class of NSMutableArray that returns an NSArray object. NSArray does not respond to the method addObject:
Try instead NSMutableArray *theArray = [NSMutableArray new];
The problem probably is on this selector:
nodeWithLibXMLNode:freeOnDealloc:
if you try to see your crash log in the console, should be written the selector unrecognized and should be this. If so check the class reference of the CXMLNode.
I checked now, and that method doesn't exists. Just a method might be useful for you in some way, that is:
- (NSArray *)nodesForXPath:(NSString *)xpath error:(NSError **)error;
Enjoy ;)

How to iterate & retrieve values from NSArray of NSArrays of NSDictionaries

I'm stumpped on how iterate and get values for an Array of Arrays of NSDictionaries (different classes/entities). Here's what I'm currently doing:
1) Constructing two separate arrays of NSDictionaries (different entities)
2) Combining both arrays with:
NSMutableArray *combinedArrayofDicts = [[NSMutableArray alloc] initWithObjects: sizesArrayOfDicts, wishListArrayOfDicts , nil];
3) Then archive combinedArrayofDicts :
NSData *dataToSend = [NSKeyedArchiver archivedDataWithRootObject:combinedArrayofDicts];
4) Transmit over GameKit
[self.session sendDataToAllPiers:dataToSend withDataMode: GKSendDataReliable error:nil];
5) How would I manage traversing thru this array on the receiving end? I want to fetch values by for each class which is key'ed by classname:
Here's how it looks via NSLog (2 Sizes Dicts, and 1 Wishlist Dict)
Printing description of receivedArray:
<__NSArrayM 0xbc65eb0>(
<__NSArrayM 0xbc651f0>(
{
classname = Sizes;
displayOrder = 0;
share = 1;
sizeType = Neck;
value = "13\" or 33 (cm)";
},
{
classname = Sizes;
displayOrder = 0;
share = 1;
sizeType = Sleeve;
value = "34\" or 86 (cm)";
}
)
,
<__NSArrayM 0xbc65e80>(
{
classname = Wishlist;
detail = "";
displayOrder = 0;
imageString = "";
latitude = "30.33216666666667";
link = "http://maps.google.com/maps?q=loc:30.332,-81.41";
longitude = "-81.40949999999999";
name = bass;
share = 1;
store = "";
}
)
)
(lldb)
In my for loop I'm issuing this:
NSString *value = [dict objectForKey:#"classname"];
and get an exception:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]:
unrecognized selector sent to instance 0xbc651f0'
Is this frowned upon as far as mixing object types in arrays of arrays?
#Will guided me to the answer with the right construct.. Here's the final answer:
NSArray *receivedArray;
if(receivedArray.count>0){
NSArray *combinedArrayofDicts = [receivedArray objectAtIndex:0];
if(combinedArrayofDicts.count>=2){
NSArray *sizesArray = [receivedArray objectAtIndex:0]; // Reference original received array
for(NSDictionary *sizeDict in sizesArray){
NSLog(#"%#",sizeDict);
}
NSArray *wishListArray = [receivedArray objectAtIndex:1]; // Reference original received array
for(NSDictionary *wishDict in wishListArray){
NSLog(#"%#",wishDict);
}
}
}
for fetching the required dictionaries use the following code,
Assume receivedArray as the array receive from Game center
NSArray *receivedArray;
if(receivedArray.count>0){
NSArray *combinedArrayofDicts = [receivedArray objectAtIndex:0];
if(combinedArrayofDicts.count>=2){
NSArray *sizesArray = [combinedArrayofDicts objectAtIndex:0];
for(NSDictionary *sizeDict in sizesArray){
NSLog(#"%#",sizeDict);
}
NSArray *wishListArray = [combinedArrayofDicts objectAtIndex:1];
for(NSDictionary *wishDict in wishListArray){
NSLog(#"%#",wishDict);
}
}
}
how iterate and get values for an Array of Arrays of NSDictionaries
As you said you have array of array of dictionaries, your current code will not retrive value of class name.
Your return values are in NSArray not in NSDictionary
So you need to do something like,
NSString *value = [returnArray[0][0] objectForKey:#"classname"];
You can iterate and get values like,
for (int i = 0; i < [returnArray count]; i++) {
for (int j = 0; j < [returnArray[i] count]; j++) {
NSDictionary *dict = (NSDictionary*)returnArray[i][j];
NSLog(#"%# ...",[dict objectForKey:#"classname"]);
}
}
Perhaps you can try:
NSString *value = [NSString stringWithFormat:#"%#",[dict objectForKey:#"classname"]];
By the looks of your output, I don't think "Sizes" is a string.

Resources