I have a cloud code on Parse.com searching a PFObject and returning it on the basis of date created the code is as follows
Parse.Cloud.define("getJournalEntry", function(request, response) {
var currDate = request.params.currDate;
var d1 = new Date(currDate + 1000 * 60 * 60 * 24 * 1); // gets 7 days ago
var query = new Parse.Query("JournalEntry");
query.greaterThan("createdAt",currDate);
query.lessThan("createdAt",d1);
query.find({
success: function(results) {
var entry = results[0];
response.success(entry);
},
error: function() {
response.error("no entry found");
}
});
});
I am trying to invoke this code from iOS app as follows
NSDate *dateOfMonth = .....;// some calculations
[PFCloud callFunctionInBackground:#"getJournalEntry"
withParameters:#{#"currDate": dateOfMonth}
block:^(PFObject *entry, NSError *error) {
if (!error) {
NSLog(entry[#"text"]);
}
else
{
NSLog(error.description);
}
}];
When checked this code from console if I supply wrong date it returns expected reply but in iOS it always crashes with following error
2014-07-16 18:18:44.343 Emojo[2845:60b] -[NSNull objectForKeyedSubscript:]: unrecognized
selector sent to instance 0x27f3068
2014-07-16 18:18:44.345 Emojo[2845:60b] *** Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[NSNull objectForKeyedSubscript:]: unrecognized selector
sent to instance 0x27f3068'
What can be the issue ?
I this will happen even on sending correct date or wrong date.
Try this may be helpfull
Updated
NSDate *dateOfMonth = [NSDate date];
NSDateFormatter *dateformat = [[NSDateFormatter alloc]init];
[dateformat setDateFormat:#"dd-MM-YYYY"];
NSMutableDictionary *dateOfMonthDic = [[NSMutableDictionary alloc]init];
[dateOfMonthDic setValue: [dateformat stringFromDate:dateOfMonth ] forKey:#"currDate"];
[PFCloud callFunctionInBackground:#"getJournalEntry"
withParameters:dateOfMonthDic
block:^(PFObject *entry, NSError *error) {
if (!error) {
NSLog(entry[#"text"]);
}
else
{
NSLog(error.description);
}
}];
Thanks & Cheers ..
Related
Hi I'm making a synchronise function that update database when receive JSON response from server. I want the import only take place if there are different data (new record or update existing record) (To increase performance) (Using coredata and magicalRecord)
Here is my JSON parser method
- (void)updateWithApiRepresentation:(NSDictionary *)json
{
self.title = json[#"Name"];
self.serverIdValue = [json[#"Id"] integerValue];
self.year = json[#"Year of Release"];
self.month = json[#"Month of Release"];
self.day = json[#"Day of Release"];
self.details = json[#"Description"];
self.coverImage = json[#"CoverImage"];
self.thumbnail = json[#"Thumbnail"];
self.price = json[#"Buy"];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"dd/MMMM/yyy"];
NSDate *date = [formatter dateFromString:[NSString stringWithFormat:#"%#/%#/%#",self.day,self.month,self.year]];
self.issueDate = date;
}
And my import method
+ (void)API_getStampsOnCompletion:(void(^)(BOOL success, NSError *error))completionBlock
{
[[ApiClient sharedInstance] getStampsOnSuccess:^(id responseJSON) {
NSManagedObjectContext *localContext = [NSManagedObjectContext MR_context];
NSMutableArray *stamps = [[NSMutableArray alloc]init];
[responseJSON[#"root"] enumerateObjectsUsingBlock:^(id attributes, NSUInteger idx, BOOL *stop) {
Stamp *stamp = [[Stamp alloc]init];
[stamp setOrderingValue:idx];
[stamp updateWithApiRepresentation:attributes];
[stamps addObject:stamp];
}];
[Stamp MR_importFromArray:stamps inContext:localContext];
} onFailure:^(NSError *error) {
if (completionBlock) {
completionBlock(NO, error);
}
}];
}
I'm getting error
CoreData: error: Failed to call designated initializer on NSManagedObject class 'Stamp'
2016-08-02 23:52:20.216 SingPost[2078:80114] -[Stamp setOrdering:]: unrecognized selector sent to instance 0x78f35a30
I have checked my Json parser is working fine. The problem is with my import method. I don't know what wrong with the function. Any help is much appreciate. Thanks!
The error message clearly describes the exact problem. You do this:
Stamp *stamp = [[Stamp alloc]init];
But init is not the designated initializer for NSManagedObject unless you added init in your subclass (which you didn't mention doing). You must call the designated initializer, which is initWithEntity:insertIntoManagedObjectContext:. There's also a convenience factory method on NSEntityDescription called insertNewObjectForEntityForName:inManagedObjectContext:. Either of those will work, but calling init will not.
I'm trying to retrieve data from web service and then filter the data and store it in another array based on a value. However, I get the following error whenever I try to filter it:
*** Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFDictionary Month]:
unrecognized selector sent to instance 0x174079640'
This is my code:
- (void)getDataHTTPClient:(Client *)client didUpdateWithData:(id)data
{
[self.view setUserInteractionEnabled:YES];
if (isPullRefresh)
{
isPullRefresh = NO;
[datasource removeAllObjects];
[self.pullToRefreshView finishLoading];
}
NSMutableArray *array = (NSMutableArray *)data;
if (![array count])
{
isNewsEnded = YES;
[self.tableView reloadData];
return;
}
[hud hide:YES];
[datasource addObjectsFromArray:(NSMutableArray *) data];
NSDate *currentDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate];
monthInt= [components month];
NSLog(#"month %li", monthInt);
NSLog(#"month after deduction %li", monthInt-1);
monthString = [NSString stringWithFormat:#"%zd",monthInt];
for (EventsBean *item in datasource)
{
if([item.Month isEqualToString:monthString])
{
[filteredArray addObject:item];
}
}
[self.tableView reloadData];
if ([datasource count])
{
[self displayNoRecordMSG:NO];
}
else
{
[self displayNoRecordMSG:YES];
}
}
the error shows on this line
if([item.Month isEqualToString:monthString])
{
[filteredArray addObject:item];
}
The data you received over the network will most likely not be an instance of EventsBean class. From the error log, it looks like it is actually a NSDictionary object. I'm guessing it is already parsed from a JSON string for you. So I would probably try to access the month property by doing item[#"Month"] instead.
for (EventsBean *item in datasource)
Here datasource contains objects of NSDictionaries and not objects of EventBeans.
Either you need to parse that dictionary and create object of EventsBean
Or
You need to do something like this
if([[item objectForKey:#"Month"] isEqualToString:monthString])
I know this question has been repeated many times. But I am getting error and I almost tried all answers and solutions.
Here is JSON:
(
{
id = 879453454392996;
name = "Test1 test1";
},
{
id = 139435345344975;
name = "Test2 test2";
}
)
I get this JSON in this way:
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me/friends"
parameters:nil];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
if (!error) {
NSLog(#"result== %#",result[#"data"]);
}
else
{
NSLog(#"Error in reading friend list");
}
}];
This works fine so far.
Now I want to put these ids inside one array. I have imported:
#import <Foundation/NSJSONSerialization.h>
I am not using any other framework.
EDIT
I tried some of the answers:
NSLog(#"result== %#",result[#"data"]);
Prints:
(
{
id = 879453454392996;
name = "Test1 test1";
},
{
id = 139435345344975;
name = "Test2 test2";
}
)
NSLog(#"name is %#", [result objectForKey:#"name"]);
retun name is (null).
NSLog(#"name is %#", [result[#"data"] objectForKey:#"name"]);
returns:
-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x17426d480
2015-09-23 15:11:35.281 myapp[1257:181878] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x17426d480'
Edit 2
OUTPUT FOR:
NSLog(#"result== %#",result);
result== {
data = (
{
id = 8795555555792996;
name = "TEST TEST";
},
{
id = 139051444474975;
name = "TEST2 TEST2";
}
);
paging = {
next = "https://graph.facebook.com/v2.4/743447008322/friends?format=json&access_token=CAAWScq3N1MCOvayeO1ocBVMzK9WiYDDavjb5nOpDnUocpzTEqDCJ2Ew8X3lLopTJ7EuidUNZChTCebTAULnGq2342RNYVcKmnoo43ssJtr6G0TQQLOTs2kkHtKL4yqu4U37GeyygPe1ZBL59I3MiEV6ju8z4bZAMUxudKRhBJFBLRJFBWZBoyHiZAOozE5oZAncZAjXf04dQEW0EZCXTa&limit=25&offset=25&__after_id=enc_AdBepNUFZAj3OmbSQddddUZCzUtPzeDuYZCO33rkZCfAZBqSkBjwrqRgvPhYEkzkVcuWu46NFLSKN5psNNsR5cIAncWg";
};
summary = {
"total_count" = 7;
};
}
You can get id by:
NSArray * arrData = result[#"data"];
for (NSDictionary * dict in arrData)
{
NSString * strID = dict[#"id"];
}
You don't need to parse the response. It's already parsed for you.
I can't figure out why this string is null inside the FQuery block. My app keeps crashing when I build the dailyLog MutableDictionary at the user key;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MMMM dd, YYYY"];
NSString *userID = [[self.userProfile objectForKey:#"userID"] copy];
self.logFirebase = [[Firebase alloc] initWithUrl:#"https://urlName.firebaseio.com/DailyLog"];
[[[self.logFirebase queryOrderedByPriority] queryEqualToValue:userID childKey:#"userID"] observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
if (![snapshot.value isEqual:[NSNull null]]) {
NSMutableArray *data = [CGCFirebaseDataExtractor extractKeysAndObjects:snapshot.value];
self.dailyLog = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"Name CONTAINS[cd] %#",[df stringFromDate:[NSDate date]]]].lastObject;
}else{
self.dailyLog = [[NSMutableDictionary alloc] init];
NSLog(#"users Profile:%#",self.userProfile);
NSLog(#"users ID :%#",[self.userProfile objectForKey:#"userID"]);
[self.dailyLog setObject:[df stringFromDate:[NSDate date]] forKey:#"date"];
[self.dailyLog setObject:[self.userProfile objectForKey:#"userID"] forKey:#"user"];
[self.dailyLog setObject:[NSNumber numberWithInt:450] forKey:#"calories"];
[[self.logFirebase childByAutoId] setValue:self.userProfile];
}
}];
EDIT:
When I log self.userProfile, I get the proper info I want. But when I log the userID itself from within the FQuery block, it's null
Here is my updated crash data:
2015-05-08 13:21:22.709 <appname>[4160:1321097] users Profile:{
"-JoirTqCXFFDY1psLTNn" = {
dateRegistered = "1431010405.81792";
userID = "304D92EF-CE77-4A10-A55F-9847153699F7";
userName = "User's Name";
};
}
2015-05-08 13:21:22.709 <appname>[4160:1321097] users ID :(null)
2015-05-08 13:21:22.714 <appname>[4160:1321097] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: object cannot be nil (key: user)'
*** First throw call stack:
(0x1852082d8 0x196a340e4 0x1850f1428 0x10007de00 0x1001454d0 0x100390fd4 0x100390f94 0x100395c28 0x1851bf7f8 0x1851bd8a0 0x1850e92d4 0x18e8ff6fc 0x189caefac 0x10007f14c 0x1970b2a08)
libc++abi.dylib: terminating with uncaught exception of type NSException
Sorry, I'm an idiot and didn't look closely at your log.
2015-05-08 13:21:22.709 <appname>[4160:1321097] users Profile:{
"-JoirTqCXFFDY1psLTNn" = {
dateRegistered = "1431010405.81792";
userID = "304D92EF-CE77-4A10-A55F-9847153699F7";
userName = "User's Name";
};
This object is evidently a dictionary in a dictionary. The first (outer) dictionary has key "-JoirTqCXFFDY1psLTNn" and that is its only key. That is why trying to get the key userID fails; that key is part of the second (inner) dictionary.
I am trying to access keys from a multi NSDictionary.
This is my output from NSLog
Berlijn[23667:60b] data = {
1 = {
data = (
4,
0,
0,
0
);
key = "June 2014";
};
}
When I try to loop through this dictionary and log the key I get NSInvalidArgumentException because key is a NSString.
This is my current code:
- (void) updateRating: (int) companyID {
APICaller *api = [[APICaller alloc] init];
[api setUrl:#"http://domain.examle/api/getcompanyhistory.php"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *parameters = #{
#"token": [[[FBSession activeSession] accessTokenData] accessToken],
#"device_token" : [defaults stringForKey:#"uniqueToken"],
#"companyid" : #(companyID)
};
[api setParameters: parameters];
[api sendPostRequest: ^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"data = %#", responseObject);
for(NSDictionary *contentData in responseObject) {
NSLog(#"contentData = %#", [contentData objectForKey:#"key"]);
}
[self.tableView reloadData];
}: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
As NSDictionary is a dictionary I don't know why it returns a string.
Update (error message):
2014-06-02 01:41:41.386 Berlijn[23747:60b] -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x1784253e0
2014-06-02 01:41:41.387 Berlijn[23747:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x1784253e0'
*** First throw call stack:
(0x1860a309c 0x192021d78 0x1860a7d14 0x1860a5a7c 0x185fc54ac 0x1000eb8ac 0x1000ea014 0x1925f0420 0x1925f03e0 0x1925f356c 0x186062d64 0x1860610a4 0x185fa1b38 0x18b9c7830 0x188fe00e8 0x1000eaff4 0x19260baa0)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Just because you call contentData a dictionary does NOT make it one.
Fast enumeration of a dictionary iterates over keys, NOT values. Your key is a string (even though you call it an NSDictionary) and will throw an exception when you try to call objectForKey: on it.
Since responseObject is a dictionary you can iterate over the keys AND values using enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop)).
Another option is to use fast enumeration correctly like so...
for(NSString *key in responseObject) {
NSLog(#"contentData = %#", [responseObject objectForKey:key]);
}