Why is my core data saving slow? - ios

Every time I try to save my NSManagedObjectContex, it takes 1-8 seconds each time. Here is my code:
- (IBAction)save
{
if (self.managedObjectContext == nil) {
self.managedObjectContext = [(RootAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
if (self.brandText.text.length == 0 || self.modelText.text.length == 0) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Please fill out the required fields" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(125, 40, 31, 7)];
NSString *path = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"bullet.png"]];
UIImage *bkgImg = [[UIImage alloc] initWithContentsOfFile:path];
[imageView setImage:bkgImg];
[alertView addSubview:imageView];
[alertView show];
} else {
Hand *a = [NSEntityDescription insertNewObjectForEntityForName:#"Hand" inManagedObjectContext:self.managedObjectContext];
a.brand = self.brandText.text;
a.caliber = self.cText.text;
self.managedObjectContext = self.app.managedObjectContext;
a.notes = self.notesView.text;
a.serialNumber = self.serialNumberText.text;
a.nickname = self.nicknameText.text;
a.model = self.modelText.text;
a.gunImage = self.image.image;
a.roundsFired = [NSString stringWithFormat:#"0"];
a.cleanRounds = [NSString stringWithFormat:#"500"];
a.showBadge = [NSNumber numberWithBool:YES];
[self dismissViewControllerAnimated:YES completion:nil];
NSError *error;
if (![self.managedObjectContext save:&error]) {
UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"There was an internal error. \n Please restart the app and try again, Thank You" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[errorAlert show];
}
}
}
The code just saves the all of the textFields text. What is the reason its so slow? Any help is greatly appreciated.

Based on your question is quite difficult to understand what is going on but I would modify the else statement as follows...
else {
Hand *a = [NSEntityDescription insertNewObjectForEntityForName:#"Hand" inManagedObjectContext:self.managedObjectContext];
a.brand = self.brandText.text;
a.caliber = self.cText.text;
// why this?
// self.managedObjectContext = self.app.managedObjectContext;
a.notes = self.notesView.text;
a.serialNumber = self.serialNumberText.text;
a.nickname = self.nicknameText.text;
a.model = self.modelText.text;
a.gunImage = self.image.image;
a.roundsFired = [NSString stringWithFormat:#"0"];
a.cleanRounds = [NSString stringWithFormat:#"500"];
a.showBadge = [NSNumber numberWithBool:YES];
NSError *error;
if (![self.managedObjectContext save:&error]) { // error during saving
UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"There was an internal error. \n Please restart the app and try again, Thank You" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[errorAlert show];
} else { // the save completes correctly, dismiss the view controller
[self dismissViewControllerAnimated:YES completion:nil];
}
}
If you want to monitor Core Data you should do it through Instrument. In addition you could set up Xcode as follows: XCode4 and Core Data: How to enable SQL Debugging.
Edit
Since the slow saving is due (based on your comment) to images, you should relies on these rules.
Core Data - Storing Images (iPhone)
Edit 2
Ok, since you don't know in advance about the size (in bytes) of your image, I really suggest to store the image in the filesystem and not in the Core Data store. In the db save only the path to your image. The image will be saved in background. This to prevent the UI to block.
Otherwise, if iOS 5 is the minimum requirement, use the External Storage flag.
How to enable External Storage for Binary Data in Core Data
Hope that helps.

Related

how to Pass recordedFile to collection view cell either by block completion or notification

Hi I have an video recored output and i want to parse it to the other controller using either blocks or nsnotification center. Here is the code used to get output.
- (void)saveRecordedFile:(NSURL *)recordedFile {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary writeVideoAtPathToSavedPhotosAlbum:recordedFile
completionBlock:
^(NSURL *assetURL, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *title;
NSString *message;
if (error != nil) {
title = #"Failed to save video";
message = [error localizedDescription];
}
else {
title = #"Saved!";
message = nil;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
NSLog(#"%#",recordedFile);'
//
}
This output i have to pass to next view controller and from this to time line same like instagram app.
one more thing is already collection view is having images
some body please help me to solve this problem

xcode display data from json web service

I am using a web service used to display details about person and profile but I don't know how to display the data from web service to labels. I have worked with login validation using web service the code is as below
-(IBAction)login:(id)sender
{
NSString *username=userName.text;
NSString *password=passWord.text;
if ([username length]!=0&&[password length]!=0)
{
NSString *link=[NSStringstringWithFormat:#"http://www.abcd.com/XXX/YYY/Login.ashx/?Username=%#&Password=%#",username,password];
NSURL *URLGet= [NSURL URLWithString:link];
NSData* data = [NSData dataWithContentsOfURL:URLGet];
NSError* error;
XYZ Return array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
if ([jasonReturnArray isEqual: #"UserId 4"])
{
Connections *view2=[[Connections alloc]initWithNibName:nil bundle:nil];
view2.modalTransitionStyle= UIModalTransitionStyleFlipHorizontal;
[self presentViewController:view2 animated:NO completion:nil];
NSLog(#"%#",jasonReturnArray);
}
else
{
UIAlertView* alert=[[UIAlertView alloc] initWithTitle:#"ERROR !!!!!!"message:#"Wrong Details" delegate:self cancelButtonTitle:#"Ok"otherButtonTitles: nil];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSLog(#"%#",jasonReturnArray);
[alert show];
}
}
else
{
UIAlertView* alert=[[UIAlertView alloc] initWithTitle:#"ERROR !!!!!!"
message:#"Wrong Details" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSLog(#"%#",jasonReturnArray);
[alert show];
}
}
It works fine but my doubt is
how to display the data from json web service to my designed labels
Create IBOutlet of your UILabel then set text value of your label as following
for (NSString * singleStringObject in jasonReturnArray)
{
yourLabel.text=[yourLabel.text stringByAppendingString:singleStringObject];
}
in case of single string you just set text of yourLabel without any loop.

BOX api - creating folders + subfolders in iOS

In the box api there's a button to make a folder. But i can't figure out how to modify the button to let me make a folder with subfolders included.
what im trying to make:
When you click the Add folder button you get a NSAlert which asks you what name you want to give it. This alert must be modified so it has multiple text bars. In the first bar you can fill in the new folders name. the other (3) you can leave blank for creating no subfolders, or fill in a name to create a subfolder.
Is this possible? I would appreciate every help or hint you can give me!
some code:
#pragma mark - Folder creation - (void)addFolderButtonClicked:(id)sender { UIAlertView *folderNamePrompt = [[UIAlertView alloc] initWithTitle:#"Add Folder" message:#"Name:" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
folderNamePrompt.alertViewStyle = UIAlertViewStylePlainTextInput;
[folderNamePrompt show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{ if (buttonIndex == alertView.firstOtherButtonIndex) { UITextField *nameField = [alertView textFieldAtIndex:0]; BoxFolderBlock success = ^(BoxFolder *folder) { [self fetchFolderItemsWithFolderID:self.folderID name:self.navigationItem.title]; };
BoxAPIJSONFailureBlock failure = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
{
NSLog(#"folder create failed with error code: %i", response.statusCode);
if (response.statusCode == 409)
{
dispatch_sync(dispatch_get_main_queue(), ^{
UIAlertView *conflictAlert = [[UIAlertView alloc] initWithTitle:#"Name conflict" message:[NSString stringWithFormat:#"A folder already exists with the name %#.\n\nNew name:", nameField.text] delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
conflictAlert.alertViewStyle = UIAlertViewStylePlainTextInput;
[conflictAlert show];
});
}
};
BoxFoldersRequestBuilder *builder = [[BoxFoldersRequestBuilder alloc] init];
builder.name = nameField.text;
builder.parentID = self.folderID;
[[BoxSDK sharedSDK].foldersManager createFolderWithRequestBuilder:builder success:success failure:failure];
}

failed to share my photo to WECHAT

I want to share a photo from the Internet to WECHAT, but after I press the share button , nothing happens , I am new to Objective-C and I am unable to figure out the problem myself.Hearing that there are a lot of experts here,so is there some guy can help me solve this one? thanks in advance. here are the codes:
UIImage * image = [[[imageTitleArray objectAtIndex:initIndex] albumImageView] image];
WXMediaMessage *message = [WXMediaMessage message];
[message setThumbImage: image];
WXImageObject *ext = [WXImageObject object];
ext.imageData = UIImageJPEGRepresentation(image,1);
message.mediaObject = ext;
SendMessageToWXReq* req = [[[SendMessageToWXReq alloc] init]autorelease];
req.bText = NO;
req.message = message;
[WXApi sendReq:req];
Try the following method
- (void) sendImageContentToWeixin:(UIImage *)image {
//if the Weixin app is not installed, show an error
if (![WXApi isWXAppInstalled]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"The Weixin app is not installed" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
return;
}
//create a message object
WXMediaMessage *message = [WXMediaMessage message];
//set the thumbnail image. This MUST be less than 32kb, or sendReq may return NO.
//we'll just use the full image resized to 100x100 pixels for now
[message setThumbImage:[image resizedImage:CGSizeMake(100,100) interpolationQuality:kCGInterpolationDefault]];
//create an image object and set the image data as a JPG representation of our UIImage
WXImageObject *ext = [WXImageObject object];
ext.imageData = UIImageJPEGRepresentation(image, 0.8);
message.mediaObject = ext;
//create a request
SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
//this is a multimedia message, not a text message
req.bText = NO;
//set the message
req.message = message;
//set the "scene", WXSceneTimeline is for "moments". WXSceneSession allows the user to send a message to friends
req.scene = WXSceneTimeline;
//try to send the request
if (![WXApi sendReq:req]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Error" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}

Getting error when calling method in AppDelegate from a button action.

When I click "save" I am getting an error when it talks back to the AppDelegate.
I'm sure, that I'm missing something small here, but if anyone has a quick answer it would be greatly appreciated.
Here's the error I'm getting:
-[AppDelegate saveNewUsername:username:]: unrecognized selector sent to instance 0x8e403d0
Here's my button action:
-(IBAction)saveButtonPressed:(id)sender
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *userid = [appDelegate retrieveFromUserDefaults:#"userid"];
NSMutableArray *currentUser = [appDelegate getUserInfo:userid];
NSString *currentUsername = [currentUser objectAtIndex:0];
NSLog(#"%#", userid);
if ([currUsername.text isEqualToString:currentUsername]) {
//here we'll check and make sure the new username is valid and doesn't already exist (for now just update local DB)
if ([theNewUsername.text isEqualToString:#""]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"You must enter something for your new username." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
} else {
int returnVal = [appDelegate saveNewUsername:userid username:theNewUsername.text];
if (returnVal == 1) {
[self dismissModalViewControllerAnimated:YES];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"There was an error saving to the database." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"The username you entered is not your current username." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
And here's my AppDelegate method:
-(int)saveNewUsername:(NSString *)user_id username:(NSString *)username
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"somedbname.sqlite3"];
FMDatabase *db = [FMDatabase databaseWithPath:writableDBPath];
if (![db open]) {
NSLog(#"Could not open db.");
return 0;
} else {
[db intForQuery:#"UPDATE user SET username=? WHERE user_id=?", username, user_id];
if ([db hadError]) {
NSLog(#"Error %d: %#", [db lastErrorCode], [db lastErrorMessage]);
return 0;
} else {
return 1;
}
}
}
Your code looks OK. So I guess appDelegate is actually not an instance of AppDelegate.
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
Set a breakpoint there and have a look in the debugger to check whether it is indeed an instance of AppDelegate.

Resources