How to convert binary data to NSData - iphone

I have converted the UIImageview into NSData and stored it as binary data. but i don't know how to retrieve the binary data to NSData and convert that to UIImageview
my code is below
image save as binary data----
-(void) save
{
UIImage *img = [UIImage imageNamed:#"back2.png"];
NSData *dataObj =UIImagePNGRepresentation(img);
NotesDetails *notesDetails = (NotesDetails *) [NSEntityDescription insertNewObjectForEntityForName:#"NotesDetails" inManagedObjectContext:managedObjectContext];
notesDetails.imageData=dataObj;
NSLog(#"NotesDetails: %#",notesDetails);
NSError *error;
if (![managedObjectContext save:&error])
{
}
}
Image Retreive------
-(void)viewDidLoad
{
NSFetchRequest *fectchreq = [[NSFetchRequest alloc] init];
NSEntityDescription *entitydes = [NSEntityDescription entityForName:#"NotesDetails"
inManagedObjectContext:self.managedObjectContext];
[fectchreq setEntity:entitydes];
NSSortDescriptor *sortdes = [[NSSortDescriptor alloc] initWithKey:#"notesTime" ascending:YES];
NSArray *sortdesarray = [[NSArray alloc] initWithObjects:sortdes, nil];
[fectchreq setSortDescriptors:sortdesarray];
NSError *error;
NSMutableArray *storeddata = [[self.managedObjectContext executeFetchRequest:fectchreq error:&error] mutableCopy];
if ([storeddata count] > 0)
{
for (NotesDetails *sc in storeddata)
{
imgFromDb=[NSData dataWithData:[#"%#",sc.imageData]];
}
}
NSLog(#"Image : %#",imgFromDb);
UIImageView *dbImage=[[UIImageView alloc]initWithFrame:CGRectMake(80,20,90,90)];
dbImage.image=[UIImage imageWithData:imgFromDb];
[NoteDetails addSubview:dbImage];
}

You can use NSKeyedUnarchiver:
imgFromDb= [NSKeyedUnarchiver unarchiveObjectWithData: sc.imageData];
And you can do the opposite (object to data) with NSKeyedArchiver if you prefer it vs UIImagePNGRepresentation().
And there are other ways to do this, for example:
imgFromDb= [UIImage imageWithData: sc.imageData];

Related

Table view and Predicates

I have a table view with 40 objects. I have to filter them by gender when Click in a UISegment (male, female and both). It seems to be working, but table view does not refresh. Please any help would be appreciatte.
-(void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = #"People";
[self loadall];
[[NSBundle mainBundle] loadNibNamed:#"FilterSortView" owner:self options:nil];
self.filterControl.selectedSegmentIndex = -1;
[self.filterControl addTarget:self action:#selector( changeSegge ) forControlEvents:UIControlEventValueChanged];
}
#
My second method to filter by gender
- (void)changeSegge
{
NSEntityDescription *personEntity = [NSEntityDescription entityForName:#"Person"
inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:personEntity];
NSError *error = nil;
self.people = [self.managedObjectContext executeFetchRequest:request error:&error];
if (error)
{
[NSException raise:NSInternalInconsistencyException format:#"Could not fetch Core Data records: %#",error];
}
if(filterControl.selectedSegmentIndex == 0){
NSPredicate *predicatem =[NSPredicate predicateWithFormat:#"gender == %#", #"m" ];
request.predicate=predicatem;
[self.tableView reloadData];
[request release];
NSLog(#"button 1");
}
Thanks a lot.
You forgot to fill people array after predicate set to fetch request.
Here is updated changeSegge method:
- (void)changeSegge
{
NSEntityDescription *personEntity = [NSEntityDescription entityForName:#"Person"
inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:personEntity];
NSError *error = nil;
self.people = [self.managedObjectContext executeFetchRequest:request error:&error];
if (error)
{
[NSException raise:NSInternalInconsistencyException format:#"Could not fetch Core Data >records: %#",error];
}
if(filterControl.selectedSegmentIndex == 0){
NSPredicate *predicatem =[NSPredicate predicateWithFormat:#"gender == %#", #"m" ];
request.predicate=predicatem;
self.people = [self.managedObjectContext executeFetchRequest:request error:&error];
[self.tableView reloadData];
[request release];
NSLog(#"button 1");
}

Only one value is being written into Core Data. Why ?

I am a newbie and I would like to store and retrieve data from a Core Data database.
I get all the data from a php file, which communicates with a SQL database. This php file returns a JSON object, which in turn is parsed by my app and then written into Core Data by doing the following:
AppDelegate.m
-(void)writeDataIntoCoreData
{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *articles = [NSEntityDescription
insertNewObjectForEntityForName:#"Articles"
inManagedObjectContext:context];
for(int i= 0; i<[json count];i++){
NSDictionary *info = [json objectAtIndex:i];
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:[info objectForKey:#"userID"]];
[articles setValue:myNumber forKey:#"articleID"];
[articles setValue:[info objectForKey:#"username"] forKey:#"author"];
[articles setValue:[info objectForKey:#"user_pic"] forKey:#"text"];
NSLog(#"Name = %#",[info objectForKey:#"username"]);
NSLog(#"Text = %#",[info objectForKey:#"user_pic"]);
}
NSError *error;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
MainViewController.m
Here I try to retrieve all the data in the Core Data database by iterating through the fetchedObjects.
-(IBAction)showCD:(id)sender
{
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Articles" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSLog(#"id: %#", [info valueForKey:#"articleID"]);
NSLog(#"Name: %#", [info valueForKey:#"author"]);
NSLog(#"Text: %#", [info valueForKey:#"text"]);
}
}
The NSLog, however, only displays one object, namely the first one that was written into the database. What is wrong ?
move your
NSManagedObject *articles = [NSEntityDescription
insertNewObjectForEntityForName:#"Articles"
inManagedObjectContext:context];
into your for loop,
for(int i= 0; i<[json count];i++){
NSManagedObject *articles = [NSEntityDescription
insertNewObjectForEntityForName:#"Articles"
inManagedObjectContext:context];
NSDictionary *info = [json objectAtIndex:i];
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:[info objectForKey:#"userID"]];
[articles setValue:myNumber forKey:#"articleID"];
[articles setValue:[info objectForKey:#"username"] forKey:#"author"];
[articles setValue:[info objectForKey:#"user_pic"] forKey:#"text"];
NSLog(#"Name = %#",[info objectForKey:#"username"]);
NSLog(#"Text = %#",[info objectForKey:#"user_pic"]);
}
Move the call to insertNewObjectForEntityForName:inManagedObjectContext: inside your loop. The way you're doing it now, you're creating just one managed object and then repeatedly change its attributes.

UIImage not being displayed when retrived from NSMutableArray

Help please :)
I have set up a mutable array as follows
- (void)viewDidLoad {
[super viewDidLoad];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"TopImage" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"topImage" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
NSMutableArray *mutableFetchResultsT = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResultsT == nil) {
}
[self setTopImageArray:mutableFetchResultsT];}
And im trying to populate a UIImageView using :
- (void)showPhoto:(NSInteger)numberToAdd
{
[topIV setImage:[topImageArray objectAtIndex:currentPI + numberToAdd]];
}
currentPI is an integer marking current image in index and number to add is set here:
- (IBAction)nextTouch
{
[self showPhoto:-1];
}
This will skip to next image (thankyou to #XenElement for this insight).
No images load in UIImageView at all.
MutableArray is getting populated through imagePickerController.
The following is my dedicated Image>Data Data>Image converter class
#implementation Image2Data
+ (BOOL)allowsReverseTransformation {
return YES;
}
+ (Class)transformedValueClass {
return [NSData class];
}
- (id)transformedValue:(id)value {
return UIImagePNGRepresentation(value);
}
- (id)reverseTransformedValue:(id)value {
return [[[UIImage alloc] initWithData:value] autorelease];
}
#end
This is initialized in my managed objects class with:
+ (void)initialize {
if (self == [Images class]) {
Image2Data *transformer = [[Image2Data alloc] init];
[NSValueTransformer setValueTransformer:transformer forName:#"Image2Data"];
}
}
Thank you in advance for any suggestions
DetartrateD
I had originally put:
[topImageArray insertObject:imageS atIndex:0];
corrected to:
[topImageArray insertObject:imageS.topImage atIndex:0];
:)))) big laugh, I was pointing to my entity not its attribute ahh well, lesson learned!
It is unlikely that you are storing the image as a UIImage object. You must be converting it into a NSData object before storing it. You must convert it back to a UIImage object using initWithData: prior to setting it to the UIImageView instance.

Cocoa Development - Having trouble loading local XML files when running from device

I have a program that runs perfectly fine when I run on the simulator, but it won't run from the device at all. Part of the initial run involves loading a few XML files into core data and it seems that these files are not being found when running on the device.
Here is the beginning of the routine that loads the file. Any help is much appreciated.
- (BOOL) checkForUpdate:(NSString *)entityName {
NSArray *thisObjectArray = nil;
NSDate *thisEntityDate = nil;
BOOL returnVal = NO;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"AppData" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *appDataArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];
AppData *thisAppData = [appDataArray objectAtIndex:0];
if ([entityName isEqualToString:#"Features"]) {
thisEntityDate = thisAppData.FeaturesUpdated;
}
else if ([entityName isEqualToString:#"DisplayTypes"]) {
thisEntityDate = thisAppData.DisplayTypesUpdated;
}
else if ([entityName isEqualToString:#"Sections"]) {
thisEntityDate = thisAppData.SectionsUpdated;
}
NSString *filePath = [[NSBundle mainBundle] pathForResource:entityName ofType:#"xml"];
NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:filePath];
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
if (doc != nil) {
// process information - this code is not being called because doc is returning nil
}
[xmlData release];
[doc release];
return returnVal;
}
Mind the case sensitivity. The device is case sensitive, whilst the simulator is not.

get NSString from NSFetchRequest issue

I'm using Core Data and I need to loop thru the result of the request, create several custom objects in the loop and store them in a NSMUtableArray, so I can send it to another view to feed a UI component. This is what I'm doing:
NSMutableArray *persons = [[NSMutableArray alloc] init];
NSError *error = nil;
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Person" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
ToggleButtonInfo *btn = [[ToggleButtonInfo alloc] init];
NSString *personName = [NSString stringWithFormat:#"ww %#", [info valueForKey:#"name"]];
NSLog(#"pn: %#", personName);
[btn setButtonInfo:personName];
[persons addObject:btn];
}
[fetchRequest release];
return persons;
The loop is working just fine, the information is there. The problem is that I get a "EXC_BAD_ACCESS" in my component if I use:
[info valueForKey:#"name"]
if I do something like this:
[btn setButtonInfo:#"something else here"];
everything works fine. So it looks like info is been de-allocated and that is causing the error, right? I try creating the scring using stringWithFormat but it doesn't work, same error.
An ideas?
Where do you get the EXC_BAD_ACCESS? I assume it's later when you're displaying the button? -setButtonInfo: probably isn't retaining, or you're over-releasing somewhere else.
Note that you're leaking btn in this code.