here is my code to edit a particular attribute and save it to the sqlite DB but i can't save the changes to the DB.
-(void)changeMemberKey
{
NSEntityDescription *entityDesc=[NSEntityDescription entityForName:#"Table1" inManagedObjectContext:context];
NSFetchRequest *request=[[NSFetchRequest alloc] init];
NSPredicate *predicate=[NSPredicate predicateWithFormat:#"(member_id=Null)"];
[request setPredicate:predicate];
[request setEntity:entityDesc];
Table1 *matches;
NSError *error;
NSArray *objects=[context executeFetchRequest:request error:&error];
NSLog(#"Object count===%d",[objects count]);
for(int i=0;i<[objects count];i++)
{
matches=[objects objectAtIndex:i];
Table1 *data=(Table1 *)matches;
NSLog(#"Data before===%#",data);
[data setValue:memberKey forKey:#"member_id"];
[context save:&error];
NSLog(#"Data after====%#",data);
data=nil;
}
entityDesc=nil;
request=nil;
matches=nil;
error=nil;
objects=nil;
}
Try to replace the for loop to
for(Table1 * data in objects)
data.member_id = memberKey;
if (! [context save:&error])
NSLog(#"Couldn't save data! Error:%#", [error description]);
Not sure whether it'll work or not, just take a try. Anyway, it's cleaner.
Related
I am making a call to an online php from my iOS app. In my output window I see the JSON Response with the data. But I need to store the NSString in my userdefaults but it is coming up NULL.
In this code the NSLog(#"JSON Response is %#", responseData); returns the json data just fine and I see the ipixid. But in the NSLog (#"ipixid is %#", ilixid); it returns ipixid is (null)
NSString *post =[[NSString alloc] initWithFormat:#"email=%#", strValue];
NSLog(#"PostData: %#",post);
NSURL *url1=[NSURL URLWithString:#"http://www.ipixsocial.com/membership/getresult.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url1];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"JSON Response is %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
// NSString *username = [(NSString *) [jsonData objectForKey:#"email"]init];
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"uid"] integerValue];
NSString* ipixid = [jsonData objectForKey:#"ipixid"];
[[NSUserDefaults standardUserDefaults] setObject:ipixid forKey:#"ipixid"];
NSLog (#"ipixid is %#", ipixid);
Don't ignore the "error" parameter you're passing to the parser. Also check that "jsonData" is not nil. I'm think that parsing is failing and because you're ignoring it and assuming jsonData is valid you're getting nil for [jsonData objectForKey:#"ipixid"];
this is the code in my AppDelegate.m:
-(IBAction)fetch:(id)sender{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Foo" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"title == 'some title'"];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {NSLog(#"Error: %#", error);}
NSMutableArray *fooArray = [[NSMutableArray alloc]init];
for (Foo *f in fetchedObjects) {
//here another fastenum for a to-many relationship
for(Bar *b in f.relationship){
[fooArray addObject:b.title];
}
}
Everytime I perform the fetch action, even if I've changed the app.storedata file via UI and checked the changes in finder, the result is always the same until i quit the application. After a restart, the fetch result is up to date and aligned with the app.storedata file. The fooArray count is always the same, regardless if I add some entries in the entities and coredata save everything.
I've tried with [fetchRequest setIncludesPendingChanges:YES] but it doesn't affect the behaviour.
How to update the fetch result while the app is running?
UPDATE: i've "solved" the problem with this workaround:
-(IBACTION)fetch:(id)sender{
_managedObjectContext = nil;
_persistenStoreCoordinator = nil;
//rest of the code...
Is this workaround a final solution? Is there a more "correct" way to solve this problem?
Okay so I ask the Core Data for a record (userKey), in that record is a PublicKey which I am extracting, however, publicKey ends up being 90% right but has a few extra characters at the beginning and is encapsulated in brackets.
I think my problem is I am getting a pointer rather than the data from the userMatches. Any guidance would be appreciated.
AppDelegate *appdelagate = [[UIApplication sharedApplication]delegate];
context = [appdelagate managedObjectContext];
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"KeyData" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
predicate = [NSPredicate predicateWithFormat:#"userKeyCD = %#", userKey];
[request setEntity:entitydesc];
[request setPredicate:predicate];
userMatches = [context executeFetchRequest:request error:&error];
NSString *publicKey = [userMatches valueForKey:#"publicKeyCD"];
Okay so I changed the last line to this and it worked fine;
NSString *publicKey = [[userMatches objectAtIndex:0] valueForKey:#"publicKeyCD"];
I did not show how it was defined but userMatches is an NSArray (sorry). It is used in a similar way further up the code;
NSArray *userMatches = [context executeFetchRequest:request error:&error];
Now I think about it is an array the right type?
I am trying to filter a fetchRequest.
I'm at the point where the result is loaded into an NSArray.
However, I need to parse the array to pull out the individual items - right now, they look as if they were one object.
The code I'm using to get to this point is:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *moc = coreDataController.mainThreadContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Category" inManagedObjectContext:moc];
[request setEntity:entity];
// Order the events by name.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
[request setSortDescriptors:#[sortDescriptor]];
// Execute the fetch -- create a mutable copy of the result.
NSError *error = nil;
NSArray *categories = [[moc executeFetchRequest:request error:&error] mutableCopy];
if (categories == nil) {
NSLog(#"bugger");
}
NSObject *value = nil;
value = [categories valueForKeyPath:#"name"];
This results as follows:
value = (
)
[DetailViewController loadPickerArray]
[AppDelegate loadPickerArray]
value = (
"Cat Two",
"Cat Three",
"Cat One",
"Cat Four"
)
Also, please note that the first time this ran, there were no results. I get that about 50% of the time.
Thanks for any help.
There are several methods you can filter your data.
The preferred way is to use a predicate for your search. This will give you the best performance.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *moc = coreDataController.mainThreadContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Category" inManagedObjectContext:moc];
[request setEntity:entity];
// Order the events by name.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name CONTAINS[CD] %#", #"Cat"]; //This will return all objects that contain 'cat' in their name property.
[request setPredicate:predicate];
[request setSortDescriptors:#[sortDescriptor]];
// Execute the fetch -- create a mutable copy of the result.
NSError *error = nil;
NSArray *categories = [moc executeFetchRequest:request error:&error];
if (categories == nil) {
NSLog(#"bugger");
}
//Here you have the objects you want in categories.
for(Category *category in categories)
{
NSLog(#"Category name: %#", category.name);
}
If you wish to filter using an array, the following is possible also:
NSMutableArray *categories = [[moc executeFetchRequest:request error:&error] mutableCopy];
[categories filterUsingPredicate:[NSPredicate predicateWithFormat:[NSPredicate predicateWithFormat:#"name CONTAINS[CD] %#", #"Cat"]]
//Now, the only objects left in categories will be the ones with "cat" in their name property.
I recommend reading the Predicates Programming Guide, as predicates are very powerful, and it is much more efficient to filter your results in the store.
I was make communication for client-server application and have strange problem.
here is a code where i pickup objects.
- (byref NSArray*)objectsOfName:(bycopy NSString*)name
withPredicate:(bycopy NSPredicate*)predicate;
{
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error = nil;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:name
inManagedObjectContext:context]];
[request setPredicate:predicate];
NSArray *results = [context executeFetchRequest:request error:&error];
[request release], request = nil;
if (error) {
NSLog(#"%#:%# Error on fetch %#", [self class], NSStringFromSelector(_cmd), error);
return nil;
}
//NSLog(#"%#:%# Result of fetch is %#", [self class], NSStringFromSelector(_cmd), results);
return results;
}
Here is pickup:
NSArray *destinations;
#ifdef SNOW_CLIENT
destinations = [server objectsOfName:#"DestinationsListWeBuy" withPredicate:predicate];
If i do
NSLog(#"Destination:%#\n",destinations);
i seen all objects in log.
If i try to do
NSLog(#"all:%#\n%#\n%#\n",[[destinations objectAtIndex:0] valueForKey:#"rate"],[[destinations objectAtIndex:0] valueForKey:#"lastUsedACD"],[[destinations objectAtIndex:0] valueForKey:#"lastUsedCallAttempts"]);
i seen attributes also.
But, if i try to do loop around objects:
for (NSManagedObject *dest in destinations)
{
NSLog(#"all:%#\n%#\n%#\n",[dest valueForKey:#"rate"],[dest valueForKey:#"lastUsedACD"],[dest valueForKey:#"lastUsedCallAttempts"]);
i have EXC_BAD_ACCESS in this part of code:
for (NSManagedObject *dest in destinations)
all debug technic, which i know, don't give me possibility to understand, what happened. (NSZombieEnabled = YES)
if i do loop at another manner:
for (NSUInteger count = 0;count < [destinations count]; count++)
NSLog(#"all:%#\n%#\n%#\n",[[destinations objectAtIndex:count] valueForKey:#"rate"],[[destinations objectAtIndex:count] valueForKey:#"lastUsedACD"],[[destinations objectAtIndex:count] valueForKey:#"lastUsedCallAttempts"]);
i seen all keys without exception. All nsmanagedobject's is subclassed.
If i need implement encodeWithCored method for all subclasses, examples is appreciated.
*UPDATE for Marcus *
This is how i receive objects from server side:
- (byref NSArray*)allObjects
{
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:#"Failed to initialize the store" forKey:NSLocalizedDescriptionKey];
[dict setValue:#"There was an error building up the data file." forKey:NSLocalizedFailureReasonErrorKey];
NSError *error = [NSError errorWithDomain:#"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
[[NSApplication sharedApplication] presentError:error];
return nil;
}
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
[moc setPersistentStoreCoordinator:coordinator];
[moc setUndoManager:nil];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:#selector(mergeChangesForClient:)
name:NSManagedObjectContextDidSaveNotification
object:thirdMOC];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Carrier"
inManagedObjectContext:moc];
[request setEntity:entity];
[request setIncludesSubentities:YES];
NSError *error = nil;
NSArray *objects = [moc executeFetchRequest:request error:&error];
[request release], request = nil;
for (NSManagedObject *carrier in objects) {
NSSet *destinations = [carrier valueForKeyPath:#"destinationsListForSale"];
for (NSManagedObject *destination in destinations) [destination addObserver:self forKeyPath:#"rate" options:NSKeyValueObservingOptionNew context:nil];
}
if (error) {
NSLog(#"%#:%# error: %#", [self class], NSStringFromSelector(_cmd), error);
return nil;
}
return objects;
}
This is what i do with them on client side:
NSArray *allObjects = [server allObjects];
[carrierArrayController setContent:allObjects];
There is no serialization in this case. Any other ways (like send copy of server moc to client side doesn't work, it just generate exceptions on main.c).
p.s. many thanks to Marcus for his Core Data book.
unrecognized selector sent to class 0x1000a2ed8 2011-03-17 02:15:18.566 snowClient[19380:903] +[AppDelegate encodeWithCoder:]: unrecognized selector sent to class 0x1000a2ed8
That is not a core data problem. That is an error in your code where you are trying to call a method on an object that does not respond to that method. You need to track that down as it appears that you are trying to serialize your AppDelegate.
Update
What kind of class is 0x1000a2ed8? Break on the exception and print out the object to see what it is. Again, this is not a core data error directly, it is sending a messages to an object that does not respond to that message. It is possible that Core Data no longer allows you to send Managed objects across as distributed objects. It is possible that this is simply an issue with an over-released object. No way to know without further investigation.
Step one: Find out what object 0x1000a2ed8 is and see if the object changes from one run to the next.