Trouble mixing UISegmentedControl with Core Data - ios

I have been searching for the answer for a couple of weaks now but I just can't seem to find it. I have been trying to get a UISegmentedControl's data to save in the Core Data but I can't do it, it keeps showing me an errors and warnings, hope you can help me.
I have something like this:
#import "DetailScoutingViewController.h"
#interface DetailScoutingViewController ()
#property (strong, nonatomic) IBOutlet UITextField *name;
#property (strong, nonatomic) IBOutlet UITextField *number;
#property (strong, nonatomic) IBOutlet UISegmentedControl *considered;
- (IBAction)save:(id)sender;
- (IBAction)cancel:(id)sender;
#property (strong, nonatomic) NSManagedObject *teamData;
#end
#implementation DetailScoutingViewController
#synthesize teamData;
- (void)viewDidLoad
{
[super viewDidLoad];
if (self.teamData) {
[self.name setText:[self.teamData valueForKey:#"name"]];
[self.number setText:[self.teamData valueForKey:#"number"]];
[self.considered setSelectedSegmentIndex:[self.teamData valueForKey:#"considered"]];
}
}
- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (IBAction)save:(id)sender {
NSManagedObjectContext *context = [self managedObjectContext];
if (self.teamData) {
// Update existing device
[self.teamData setValue:self.name.text forKey:#"name"];
[self.teamData setValue:self.number.text forKey:#"number"];
[self.teamData setValue:self.considered.selectedSegmentIndex forKey:#"considered"];
} else {
// Create a new device
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:#"Teams" inManagedObjectContext:context];
[newDevice setValue:self.name.text forKey:#"name"];
[newDevice setValue:self.number.text forKey:#"number"];
}
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)cancel:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
The UITextField's data saves without a problem, the only problem I have is the UISegmentedControl. What should I do?

[self.teamData valueForKey:#"considered"]
This returns what is likely to be an NSNumber instance, but setSelectedSegmentIndex: expects an NSInteger so you should be using:
[self.considered setSelectedSegmentIndex:[[self.teamData valueForKey:#"considered"] integerValue]];
You also need to change the corresponding save code to:
[self.teamData setValue:[NSNumber numberWithInteger:self.considered.selectedSegmentIndex] forKey:#"considered"];
This bit of code is not helping:
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
change to:
if ([delegate respondsToSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
At some point in some other controller you should be setting ...teamData = .... If you aren't, then your controller will always be creating a new Teams managed object and inserting it into the data store. In this case, you don't set the self.considered.selectedSegmentIndex so you will never store it. It's only ever stored when you already have a Teams object.

Related

No visible #interface for 'NSManagedObjectContext' declares

[self.managedObjectContext deletedObjects:lastPoint];
This line shows me an error
No visible #interface for 'NSManagedObjectContext' declares the selector 'deletedObjects'.
Here is my code
can any one solve this?
Appdelegate.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
Appdelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
/* crete the fetch request first*/
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:#"Rectangle"];
NSError *requestError = nil;
/*And execute the fetch request on the context*/
NSArray *rectangle = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
/*make sure we get the array*/
if ([rectangle count] > 0) {
/*delete the last person in the array*/
Rectangle *lastPoint = [rectangle lastObject];
[self.managedObjectContext deletedObjects:lastPoint];
if ([lastPoint isDeleted]) {
NSLog(#"Successfully deleted the last point...");
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError]) {
NSLog(#"successfully saved the context");
} else {
NSLog(#"Failed to save the context");
}
} else {
NSLog(#"Failed to delete the last point");
}
} else {
NSLog(#"Could not find any rectangle entities in the context.");
}
return YES;
}
The error message
No visible #interface for 'NSManagedObjectContext' declares the
selector 'deletedObjects'.
tells you that the class NSManagedObjectContext doesn't implement the method deletedObjects. You can check this in the API documentation.
You can use deleteObject: to delete single objects. So change your code to:
[self.managedObjectContext deleteObject:lastPoint];
As the documentation says deletedObjects is the read only property, so it has only getter method without any parameters
So you should access it just by using next
self.managedObjectContext.deletedObjects

Not able to display results in the console

I made an application for storing data in CD. I want to just simply write the things into the console but I can't get printed on the console. Am I doing something wrong?
Here is my code whole demo application.
Here is my screen shot of Core_Data_Demo_xcdatamodeld
// AppDelegate.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
// AppDelegate.h
-(BOOL)createNewRectangleWithHeight:(NSInteger)heightParam width:(NSInteger)widthParam{
if (heightParam ==0 || widthParam ==0) {
NSLog(#"The height and width must no be 0");
return NO;
}
Rectangle *rect = [NSEntityDescription insertNewObjectForEntityForName:#"Rectangle" inManagedObjectContext:self.managedObjectContext];
if (rect == nil) {
NSLog(#"Failed to create new Rectangle");
return NO;
}
rect.height = [NSNumber numberWithInt:heightParam];
rect.width = [NSNumber numberWithInt:widthParam];
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError]) {
return YES;
} else {
NSLog(#"Failed to save new person. Error = %# ",savingError);
}
return YES;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self createNewRectangleWithHeight:2 width:2];
return YES;
}
You are not able to see any statements because (I suppose) things run correctly.
If you want to retrieve data and print in the console you need to run a different method like printData or whatever you want. This method should set up a NSFetchRequest and execute it against your entity Rectangle.
- (void)printData {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Rectangle"];
NSError *error = nil;
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];
if(error) {
// An error occurred
} else {
// See the results
}
}
Usage
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// [self createNewRectangleWithHeight:2 width:2];
[self printData];
return YES;
}
You should comment the createNew... method otherwise you will see multiple entries (equal to the number of times you've run the application) of Rectangle objects with the same width and height.
The code which you have shown is for adding values using core data, If you do not get any error in the NSError object while you are adding the values then data is successfully added inside the sqlite file.
To check the added values what you can do is use the SqliteManager addon from firefox and open the sqlite file (You can get the sqlite file location using NSHomeDirectory() method for it and then jump to the documents folder).
If you don't want the addon way you can always use NSFetchRequest to pull your data given below is the code for the same
- (NSManagedObjectContext*)getManagedObjectContext{
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
return appDelegate.managedObjectContext;
}
- (void)fetchdataFromDatabase{
NSManagedObjectContext *appContext = [self getManagedObjectContext];
if(appContext!=nil){
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"YOUR_ENTITY_NAME" inManagedObjectContext:appContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [appContext executeFetchRequest:fetchRequest
error:&error];
if(error!=nil && fetchedObjects.count!=0){
// print your data here
}else{
//Print the error here
}
}
}

Error and Crash when using the Core Data to create a UITableView

I try to use Core Data to make a UITableView, but I come across a crash when I run it:
014-07-29 10:13:12.443 TableAndCoreData[797:60b] -[AppDelegate managedObjectContext]: unrecognized selector sent to instance 0x8f319a0
2014-07-29 10:13:12.446 TableAndCoreData[797:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AppDelegate managedObjectContext]: unrecognized selector sent to instance 0x8f319a0'
I generally check it and I guess it might be the problem of the creating the managedObjectContext. Does any one have some idea to help me to fix this problem?
#interface DetailViewController ()
#property (weak, nonatomic) IBOutlet UITextField *nameTextField;
#property (weak, nonatomic) IBOutlet UITextField *ageTextField;
#end
#implementation DetailViewController
// Set NSManagedObjectContext
- (NSManagedObjectContext *) managedOjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication]delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedOjectContext];
}
return context;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)cancelButton:(UIButton *)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)saveButton:(UIButton *)sender
{
[self save];
}
- (void)save
{
// Get ManagedObjectContext
NSManagedObjectContext *context = [self managedOjectContext];
// Create a ManagedObject
NSManagedObject *aPerson = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:context];
// Set value for the attributes of the entity
[aPerson setValue:self.nameTextField.text forKey:#"name"];
[aPerson setValue:self.ageTextField.text forKey:#"age"];
// Check the error
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't save due to %#%#", error, [error localizedDescription]);
}
[self dismissViewControllerAnimated:YES completion:nil];
}
Besides, I am trying another way to create UITableView using Core Data:
- (void) save
{
// Create UIManagedDocument
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentDirectory = [[fileManager URLsForDirectory:NSDocumentationDirectory inDomains:NSUserDomainMask]firstObject];
NSString *documentName = #"Model";
NSURL *url = [documentDirectory URLByAppendingPathComponent:documentName];
UIManagedDocument *document = [[UIManagedDocument alloc]initWithFileURL:url];
if ([fileManager fileExistsAtPath:[url path]]) {
[document openWithCompletionHandler:^(BOOL success) {
if (success) {
if (document.documentState == UIDocumentStateNormal) {
// Get a ManagedObjectContext
NSManagedObjectContext *context = document.managedObjectContext;
// Set managed object (entity)
NSManagedObject *aPerson = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:context];
// Set value for the attribute (which are "name" and "age") of the entity
[aPerson setValue:self.nameTextField.text forKey:#"name"];
[aPerson setValue:self.ageTextField.text forKey:#"age"];
// Check whether there is an error
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't save due to %#%#", error, [error localizedDescription]);
}
// Close the window
[self dismissViewControllerAnimated:YES completion:nil];
}
}
if (!success) {
NSLog(#"couldn't open document at %#", url);
}
}];
}
else {
[document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
if (document.documentState == UIDocumentStateNormal) {
// Get a ManagedObjectContext
NSManagedObjectContext *context = document.managedObjectContext;
// Set managed object (entity)
NSManagedObject *aPerson = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:context];
// Set value for the attribute (which are "name" and "age") of the entity
[aPerson setValue:self.nameTextField.text forKey:#"name"];
[aPerson setValue:self.ageTextField.text forKey:#"age"];
// Check whether there is an error
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't save due to %#%#", error, [error localizedDescription]);
}
// Close the window
[self dismissViewControllerAnimated:YES completion:nil];
}
}
if (!success) {
NSLog(#"couldn't open document at %#", url);
}
}];
}
}
However, it just couldn't find the UIManagedDocument. I really wonder the reason why I should create a UIManagedDocument and the document name I should name it.
Your crash does not have anything to do with Core Data.
Change this:
[delegate performSelector:#selector(managedObjectContext)]
to:
[delegate respondsToSelector:#selector(managedObjectContext)]
The crash was happening because you were sending the message managedObjectContext to the application delegate object, which does not respond to that message. It was being sent because where you meant to check to see if it responds to that message with respondsToSelector:, you had performSelector instead. Your application delegate object still needs to implement managedObjectContext for your code to be functional, but the portions you have posted should no longer crash as you describe.
In general you want to avoid calling a method on the application delegate this way. It's preferred to pass a value like this from the application delegate into the root view controller at startup, and it's passed along to the next view controller and the next.
There is a slightly outdated, but still relevant section of the Core Data documentation that discusses this:
A view controller typically shouldn’t retrieve the context from a global object such as the application delegate—this makes the application architecture rigid. Neither should a view controller create a context for its own use (unless it’s a nested context).
...as well as the iOS 5 release notes:
Nested contexts make it more important than ever that you adopt the “pass the baton” approach of accessing a context (by passing a context from one view controller to the next) rather than retrieving it directly from the application delegate.

iOS: CoreData save and search NSEntityDescription or kSetAttrDescription

Im new to Objective-C and CoreData and want to learn it and im trying in Xcode 5, im trying to make this tutorial.
I have followed it with some other CoreData table name, but i get some errors with my "ViewController.m" and dont know what to changes, i can see it recomment to changes "NSEntityDescription" to "kSetAttrDescription" but dont know if thats right or wrong to do, hope someone can tell mewhat to do - so i know it next time.
Error issues
Error Descriptions
My ViewController.m code.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//Save data as CoreData, to CoreData Table "Kunder" field "navn", "adresse", "alder" from textfield _name.text, _adress.text, _age.text.
- (IBAction)saveData:(id)sender {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newContact;
newContact = [NSEntityDescription insertNewObjectForEntityForName:#"Kunder" inManagedObjectContext:context];
[newContact setValue: _name.text forKey:#"navn"];
[newContact setValue: _adress.text forKey:#"adresse"];
[newContact setValue: _age.text forKey:#"alder"];
//if textfield empty, then error else save and show label message "Kunde Gemt".
_name.text = #"";
_adress.text = #"";
_age.text = #"";
NSError *error;
[context save:&error];
_status.text = #"Kunde Gemt";
}
//Find-search for user by name.
- (IBAction)findKunde:(id)sender {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"Kunder" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred =
[NSPredicate predicateWithFormat:#"(navn = %#)", _name.text];
[request setPredicate:pred];
NSManagedObject *matches = nil;
//if no user then error, else take name match and get "adresse" and "alder" from CoreData and show it in the text fields _adress.text and _age.text and show matche count in status label.
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if ([objects count] == 0) {
_status.text = #"Ingen fundet";
} else {
matches = objects[0];
_adress.text = [matches valueForKey:#"adresse"];
_age.text = [matches valueForKey:#"alder"];
_status.text = [NSString stringWithFormat: #"%lu antal fundet", (unsigned long)[objects count]];
}
}
#end
My ViewController.h page (no error)
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#interface ViewController : UIViewController
#property (strong, nonatomic) IBOutlet UITextField *name;
#property (strong, nonatomic) IBOutlet UITextField *adress;
#property (strong, nonatomic) IBOutlet UITextField *age;
#property (strong, nonatomic) IBOutlet UILabel *status;
- (IBAction)saveData:(id)sender;
- (IBAction)findKunde:(id)sender;
#end
My AppDelegate.m file
#import "AppDelegate.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
return YES;
}
....
#end
UPDATE
When adding text to the fields and hit save, i don get a "Save ok" message it jump to xcode and show me this.
Is seems that you forgot to import <CoreData/CoreData.h>.
You can add the import to your precompiled header (...-Prefix.pch) file
which would look similar to this:
#import <Availability.h>
#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h> // <-- Add this !!
#endif
You might also have to add the "CoreData.framework" to the "Link Binary With Libraries"
section of the targets "Build Phases".

Multiple downloading progress bar objective c

I am developing a messaging client (as Whatsapp or Line).
I am in troubles because I need to support multiple-downloading files (and uploading), showing a progress bar into each message that have a current downloading process.
The multi-download and upload process is already developed (and works fine), the issue comes when I try to show that progress into the message progress bar.
My "solution" (I don't know if there is a better way to do it) is adding a field "uploaded" and other "downloaded" into the Message entity in CoreData, which save the upload percent or the download percent, and update that field each time that NSURLConnection calls (in upload progress, in download is different):
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
but if I try to update the CoreData context inside that method, my user interface freeze.
Ok, that is my problem, I am going to show you the code:
This is my Core Data Message entity:
#property (nonatomic, retain) NSString *ident;
#property (nonatomic, retain) NSString *localId;
#property (nonatomic, retain) NSString *body;
#property (nonatomic, retain) NSString *contentSize;
#property (nonatomic, retain) NSNumber *uploaded;
#property (nonatomic, retain) NSNumber *downloaded;
#property (nonatomic, retain) Avatar *avatar;
#property (nonatomic, retain) Thumbnail *thumbnail;
Here is my class to manage every HTTP connection and here I try to update that entity.
#implementation HTTPConnection
//SOME CODE...
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
if (self.localId) {
float progress = (float)totalBytesWritten/(float)totalBytesExpectedToWrite;
[self performSelectorOnMainThread:#selector(saveProgressInDatabase:) withObject:[NSNumber numberWithFloat:progress] waitUntilDone:YES];
}
}
- (void)saveProgressInDatabase:(NSNumber *)progress
{
NSManagedObjectContext *context = [[[AppDelegate alloc]init]managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:MESSAGE_ENTITY
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"localId = %#", self.localId];
[fetchRequest setPredicate:predicate];
NSError *coreError = nil;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&coreError];
Message *currentMessage = [fetchedObjects objectAtIndex:0];
[currentMessage setUploaded:progress];
[context save:&coreError];
[[NSNotificationCenter defaultCenter] postNotificationName:UPLOAD_UPDATED_NOTIFICATION object:self];
}
And here I show the message list and send the messages in a table view:
#implementation TimelineViewController
//SOME CODE...
- (void)viewWillAppear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(updateTable)
name:UPLOAD_UPDATED_NOTIFICATION
object:nil];
}
- (void)updateTable
{
NSError *error;
[[self fetchedResultsController] performFetch:&error];
if ([[_fetchedResultsController sections]count]>0) {
[table reloadData];
NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:([table numberOfRowsInSection:[[_fetchedResultsController sections]count]-1] - 1) inSection:[[_fetchedResultsController sections]count]-1];
[table scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}
}
//SOME CODE...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Message *info = [_fetchedResultsController objectAtIndexPath:indexPath];
//MORE CODE...
if ([info contentSize]!=NULL) {
[cell.progressBar setHidden:NO];
[cell.progressBar setProgress:[[info uploaded]floatValue]];
}
}
//CODE...
- (IBAction)sendMessageAction:(id)sender
{
CommandServices *services = [[CommandServices alloc]init];
[services sendMessageToGroup:message withMedia:attachedMedia withLocalId:localId];
}
I don't know if that is enough to understand my issue, so I am going to ask two main questions:
Is that a nice way to manage multiple-download with multiple progress bar? I mean, saving the progress into the entity... Or, how could I do it?
Why my app is freeze when I upload or download a file? Maybe I am doing too many access to CoreData?
Thanks so much!
My guess is that you should use the following code to get the NSManagedObjectContext:
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [app managedObjectContext];
instead of:
NSManagedObjectContext *context = [[[AppDelegate alloc]init]managedObjectContext];
Well...after few days thinking about my issue, I realize I was doing too many database access and because of that my app freeze.
I solved it passing to my HTTPConnection object, an instance of the progress bar I want to manage. And I save the progress download/upload only when finishing.
So that is my solution:
In HTTPConnection:
+ (void)setProgressBar:(UIProgressView *)progress
{
[downloadConnection setProgressBar:progress];
}
//CODE...
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
float progress = (float)totalBytesWritten/(float)totalBytesExpectedToWrite;
if (self.progressBar) {
self.progressBar.progress = progress;
}
if (progress == 1.0) {
[self saveProgressInDatabase:[NSNumber numberWithFloat:progress]];
}
}
And in my message list:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Message *info = [_fetchedResultsController objectAtIndexPath:indexPath];
//MORE CODE...
if (([info contentSize]!=NULL)&&([[info uploaded]floatValue]<1.0)) {
[HTTPConnection setProgressBar:cell.progressBar];
[cell.progressBar setHidden:NO];
} }
Thanks for your help!

Resources