Get Values form text Fields in UITableView Custom Cell - iphone

I have Created a custom UITableViewCell, the cell has multiple text fields, now i want to access the strings or data in these UITextFields. I know i can get the cell on didSelectRowAtIndexPath, but i need to get the text on a "Save" method.

Suppose you have four text fields with tags 100 and so on to 104.
You will you Counter that shows how many cells you have in tableview.
 
       
for (int i=0; iLessThanCounter; i++) {
       
 NSIndexPath *indexPath = [NSIndexPath indexPathForRow: i inSection: 0];
           
UITableViewCell *cell = [mytableview cellForRowAtIndexPath:indexPath];
           
for (UIView *view in  cell.contentView.subviews){                
               
      if ([view isKindOfClass:[UITextField class]]){
                   
             UITextField* txtField = (UITextField *)view;
                   
             if (txtField.tag == 100) {
                    NSLog(#"TextField.tag:%u and Data %#", txtField.tag, txtField.text);
             }
             if (txtField.tag == 101) {
                   NSLog(#"TextField.tag:%u and Data %#", txtField.tag, txtField.text);
             }
             if (txtField.tag == 102) {
                  NSLog(#"TextField.tag:%u and Data %#", txtField.tag, txtField.text);
             }
             if (txtField.tag == 103) {
                  NSLog(#"TextField.tag:%u and Data %#", txtField.tag, txtField.text);
             }
             if (txtField.tag == 104) {
                  NSLog(#"TextField.tag:%u and Data %#", txtField.tag, txtField.text);
             } // End of isKindofClass
         } // End of Cell Sub View
    }// Counter Loop
}

You can simply use viewWithTag to get your desired views. Suppose you have one imageview with tag 100 and one text view with tag 200.
UITableViewCell *cell = [mytableview cellForRowAtIndexPath:indexPath];
UIImageView *getImageView = (UIImageView*)[cell.contentView viewWithTag:100];
UITextField *getTextView = (UITextField*)[cell.contentView viewWithTag:200];

you need to create instance for each textField in your header file. Look at this sample demo
http://windrealm.org/tutorials/uitableview_uitextfield_form.php
You can access textfield's text property for getting the text value for a particular textfield

Related

uitableview tags are not working ? Using two tableviews in one uiviewcontroller?

I am using two tableviews in one view controller, both tables having separate data.
When I implemented the tableview delegate methods, the code is working for only tag1 not for tag2.
I have used almost all possible solution available on StackOverflow but still facing this issue. Here is my code for tableView:cellForRowAtIndexPath:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView.tag==1){
        
        static NSString *myIdentiFier=#"myIdentiFier";
        productCell *cell=(productCell *)[tableView dequeueReusableCellWithIdentifier:myIdentiFier];
        if(!cell){
            NSArray *cellObjs=[[NSBundle mainBundle]loadNibNamed:#"productCell" owner:self options:nil];
            for(id obj in cellObjs){
                if([obj isKindOfClass:[productCell class]]){
                    cell=(productCell *)obj;
                    break;
                }
            }
            cell.productTitle.text=[nameArray objectAtIndex:indexPath.row];
            [cell.productImage setImageWithURL:[NSURL URLWithString:[productImageArray objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:#"rsz_no-image"]];
        }
        
        return cell;
    }
    else{
        static NSString *mileIdentifier=#"mileIdentifier";
        mileStoneTableViewCell *mcell=(mileStoneTableViewCell *)[tableView dequeueReusableCellWithIdentifier:mileIdentifier];
        if(!mcell){
            NSArray *cellObjs=[[NSBundle mainBundle]loadNibNamed:#"mileStoneTableViewCell" owner:self options:nil];
            for(id obj in cellObjs){
                if([obj isKindOfClass:[mileStoneTableViewCell class]]){
                    mcell=(mileStoneTableViewCell *)obj;
                    break;
                }
            }
            mcell.mile_description.text=[mileStoneDescr objectAtIndex:indexPath.row];
            
        }
        
        return mcell;
    }
}
keep a reference to each of the table views
//viewcontroller.h
#property (nonatomic, weak) IBOutlet UITableView* firstTableView;
#property (nonatomic, weak) IBOutlet UITableView* secondTableView;
In the datasource/ delegate methods you need to account for the fact that the method needs to behave differently depending on which table view is in use. e.g.
//viewcontroller.m
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
if (tableView == self.firstTableView) {
...
} else { // tableView == self.secondTableView
...
}
}
return cell;
}
Please note the following:
1. Have you called [self.secondTableView reloadData].
2. Try NSLog(#"%d", self.secondTableView.tag) to make sure that the tag is set correctly.
3. Have you used interface builder to set the tag or did you set it programatically? If you have set it programatically, make sure you have set the tag before you call reloadData.
4. Finally make sure your dataSource and delegate is set correctly.
5. If you have two tableViews, it is advisable not to set the dataSource and Delegate of both the tableViews by control dragging in Interface Builder. In some cases that may cause the app to crash. Set either one or both of the tableView's datasource and delegate programatically.
If all this is correct you code should work.

Saving photos to custom library

My problem is really annoying. I'm creating app which takes photos and need to save them to custom gallery. I've found a couple of tutorials how to do this with AlAssetsLibrary but there is one, big problem... There is no saveImage:toAlbum:withCompletionBlock: method. I've used addAssetsGroupAlbumWithName:resultBlock:failureBlock: to create custom photo album but there is no way I can save images to this gallery! I'm using iOS 6 iPhone 4.
Any ideas!?
The method you mentioned in the question saveImage:toAlbum:withCompletionBlock is not part of ALAssetsLibrary. This method is written in ALAssetLibary's category. You got to import the category in your class to use the method.
To learn more about objective C category , check out the developer reference.
Look at here:
http://www.touch-code-magazine.com/ios5-saving-photos-in-custom-photo-album-category-for-download/
And there is a Stackoverflow Thread here: Save Photos to Custom Album in iPhones Photo Library
If you are using AssetsLibrary you can write this code
- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerController *imagePicker;
if (buttonIndex < 2)
{
        self.library = [[[ALAssetsLibrary alloc] init] autorelease];
        
        self.imageEditor = [[[DemoImageEditor alloc] initWithNibName:#"DemoImageEditor" bundle:nil] autorelease];
        
        self.imageEditor.doneCallback = ^(UIImage *editedImage, BOOL canceled){
            if(!canceled)
            {
                anotherImage = true;
                
                NSString *imageName;
               
                imageName =#"Abc.jpg";
                
                UIImageWriteToSavedPhotosAlbum(editedImage, self, #selector(image:didFinishSavingWithError:contextInfo:), nil);
                editedImage = [self scaleImage:editedImage toSize:CGSizeMake(600,600)];
                 [[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(editedImage)forKey:#"image"];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    UIAlertView *alert;
    
   if (error)
        alert = [[UIAlertView alloc] initWithTitle:#"Error" 
                                           message:#"Unable to save image to Photo Album." 
                                          delegate:self cancelButtonTitle:#"Ok" 
                                 otherButtonTitles:nil];
else 
        alert = [[UIAlertView alloc] initWithTitle:#"Success" 
                                           message:#"Image saved to Photo Album." 
                                          delegate:self cancelButtonTitle:#"Ok" 
                                 otherButtonTitles:nil];
    [alert release];
}
It will solve your case.

how to adjust the height of a cell when loading from the custom tableview cell classes?

I have an application in which i am adding 2 types of cells in two designs. So I am using custom UITableViewCell object classes. But my problem is I am using a text view in this cells. I need to adjust the row height according to its content size. This is what my code looks like:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier1 = #"CellIdentifier";
    static NSString *CellIdentifier2 = #"Cell";
        
    if(messagesarray==nil||[messagesarray count]==0)
    {
        
    }
   else
    {
       NSMutableDictionary *dicttable=[messagesarray objectAtIndex:indexPath.row];
        NSString *head=[dicttable objectForKey:#"gfgfg"];
        NSString *head1=[dicttable objectForKey:#"gfgfgf"];
       if([type isEqualToString:#"m"])    
        {
       if([head isEqualToString:#"NA"])
          {
             
              CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
             if (cell == nil)
            {
            cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier1] autorelease];
            cell.backgroundView = [ [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"white_top_portion.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ]autorelease];
            }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.nameLabel.text=head;
        cell.msg.text=head1;
        [cell.button addTarget:self action:#selector(callAction:) forControlEvents:UIControlEventTouchUpInside];     
              
              if(icon!=nil)
              {
                  if(![[ImageCache sharedImageCache] hasImageWithKey:icon])
                    {
  cell.myImageView.image = [UIImage imageNamed:#"fggtgf.png"];
                      NSArray *myArray = [NSArray arrayWithObjects:cell.myImageView,icon,#"fgfgfg.png",[NSNumber numberWithBool:NO],nil];
                      AppDelegate *appDelegate = (AppDelegate  *)[[UIApplication sharedApplication] delegate];
                      [appDelegate performSelectorInBackground:#selector(updateImageViewInBackground:) withObject:myArray];   
                    }
                  else 
                  {
                      cell.myImageView.image = [[ImageCache sharedImageCache] getImagefromCacheOrUrl:icon];
                    }
              }
              else
              {
                  cell.myImageView.image = [UIImage imageNamed:#"fgfgfg.png"];  
                  
              } 
         
        cell.label.text=sub;   
         return cell;
          }
         else
         {
            Customcellwithimage *cell = (Customcellwithimage *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
             
             if (cell == nil)
             {
                 cell = [[[Customcellwithimage alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier2] autorelease];
                 cell.backgroundView = [ [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"white_deal_bg.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ]autorelease];
             }
             
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
             cell.datelabel1.text=subtitle;
              cell.nameLabel1.text=head;
             cell.msg1.text=head1;
             if(icon!=nil)
             {
                 if(![[ImageCache sharedImageCache] hasImageWithKey:icon])
                  {
cell.myImageView1.image = [UIImage imageNamed:#"fgfgfgf.png"];
                     NSArray *myArray = [NSArray arrayWithObjects:cell.myImageView1,icon,#"fgfgfgf.png",[NSNumber numberWithBool:NO],nil];
                     MFAppDelegate *appDelegate = (MFAppDelegate  *)[[UIApplication sharedApplication] delegate];
                     [appDelegate performSelectorInBackground:#selector(updateImageViewInBackground:) withObject:myArray];   
                     
                 }
                 else 
                 {
                     cell.myImageView1.image = [[ImageCache sharedImageCache] getImagefromCacheOrUrl:icon];
                  }
             }
             else
             {
                 cell.myImageView1.image = [UIImage imageNamed:#"fgfgfgf.png"];  
             } 
              
             cell.cellview1.image=[UIImage imageNamed:#"vf.png"];
cell.label1.text=sub;
[cell.button1 addTarget:self action:#selector(callAction:) forControlEvents:UIControlEventTouchUpInside]; 
              cell.bannerview1.image=[UIImage imageNamed:#"vfgf.png"];
              return cell;
}
        }              
    }  
}
       
 can anybody help me in achieving the row height as different for different cells?.I have to find out the height in - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPathand i tried a method will need to find out the cell object of the current row.but didnt succeed .can anybody guide me in right direction
I think you are looking for - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath - Here you can calculate the height for each individual row.
Note, if the calculation is a lot of work, you might see a reduction in performance. If this is the case you can pre-calculate the values and store them.
You can use this method for variable height support for your application.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
Whenever you want to set the height dynamically, call this method with your tableview object.
For more info Click Here
or use this method with other tableview delegate methods.
Cell resizing can get pretty complicated, especially when UITextViews are involved. I suggest you simply use a table view framework such as Sensible TableView, where all the cells are automatically resized to fit contents. I believe they also now have a free version.

NSInternalInconsistencyException ( error during execution of SQL string 'INSERT INTO Y_UBMETA(YPEERID, YTRANSACTIONNUMBER) )

iOS iCloud
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'error during execution of SQL string 'INSERT INTO Y_UBMETA(YPEERID, YTRANSACTIONNUMBER)
Unresolved error Error Domain=NSCocoaErrorDomain Code=134312 "Store metadata recovery appears to have failed, please try adding the store to the coordinator again. If that is unsuccessful, migrate the data to a new ubiquitized persistent store." UserInfo=0xdba5b80 {NSLocalizedDescription=Store metadata recovery appears to have failed, please try adding the store to the coordinator again. If that is unsuccessful, migrate the data to a new ubiquitized persistent store.}, {
   NSLocalizedDescription = "Store metadata recovery appears to have failed, please try adding the store to the coordinator again. If that is unsuccessful, migrate the data to a new ubiquitized persistent store.";
How do I solve this problem? Coz that it is an internal query for iCloud. I am putting my code block below of the method i have written..
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    NSLog(#"persistentStoreCoordinator:%#",[persistentStoreCoordinator_ description]);
    if((persistentStoreCoordinator_ != nil))
    {
        return persistentStoreCoordinator_;
    }
    NSLog(#"persistentStoreCoordinator:%#",[persistentStoreCoordinator_ description]);
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"CoreDataModel.sqlite"];
    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSPersistentStoreCoordinator* psc = persistentStoreCoordinator_;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
   
           
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        // Migrate datamodel
        NSDictionary *options = nil;
        // this needs to match the entitlements and provisioning profile
        NSURL *cloudURL = [fileManager URLForUbiquityContainerIdentifier:nil];
        NSLog(#"cloudURL:%#",cloudURL);
            //NSString* coreDataCloudContent = [[cloudURL path] stringByAppendingPathComponent:#"Data"];  
           
           cloudURL = [cloudURL URLByAppendingPathComponent:#"Data"];                                                                                                                                  
       // NSLog(#"coreDataCloudContent:%#",coreDataCloudContent);
       //if ([coreDataCloudContent length] != 0 && [[defaults objectForKey:#"allMetadataFlag"] isEqualToString:#"YES"])
           
       if (cloudURL )//&& [[defaults objectForKey:#"allMetadataFlag"] isEqualToString:#"YES"])
           
        {
            // iCloud is available
           // cloudURL = [NSURL fileURLWithPath:coreDataCloudContent];
            NSLog(#"cloudURL:%#",cloudURL);
            options = [NSDictionary dictionaryWithObjectsAndKeys:
                       [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                       [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                       #"SecureAssistant.store", NSPersistentStoreUbiquitousContentNameKey,
                       cloudURL, NSPersistentStoreUbiquitousContentURLKey,nil];
        }
        else
        {
            // iCloud is not available
            options = [NSDictionary dictionaryWithObjectsAndKeys:
                       [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                       [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,nil];
        }
            NSError *error = nil;
        [psc lock];
        if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
        {
            NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
            abort();
        }
        [psc unlock];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(#"asynchronously added persistent store!");
            [[NSNotificationCenter defaultCenter] postNotificationName:#"RefetchAllDatabaseData" object:self userInfo:nil];
        });
    });
   
   return persistentStoreCoordinator_;
}
I have got the same issue, it happened because i have changed the attribute of datamodel from Xcode, not from my app by code. i solved this by delete the SQLite file from iCloud and deleted the app from device then rebuild. It worked for me.

why App crashes getting data from Dictionary?

I am working on an app and i have to save some data in the dictionary and then i have to load that data and showing to user whatever the options user saved.
when i get data from dictionary it crashes on second time not on first time and gives different crash log every time.
like
-[UIDeviceRGBColor objectAtIndex:]: unrecognized selector sent to instance 0x68c22d0
or
[UIControlTargetAction count]: unrecognized selector sent to instance 0x68683d0
or
0 : <CFString 0x687cb30 [0x124eb38]>{contents = "dish1"} = UIDeviceWhiteColorSpace 0 0.5
my code is this
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   if (tableView == menuTableView) {
       [optionsView addSubview:topScrollView];
       optionFlag=NO;
       [self optionScreenMethod:indexPath.row];
       NSString *dishSelect=[NSString stringWithFormat:#"dish%d",indexPath.row];
       NSMutableArray *dishesArray=[[NSMutableArray alloc]init];
       NSMutableArray *dishDicArray=[[NSMutableArray alloc]init];
       dishesArray=[dishDictionary objectForKey:dishSelect];
       NSLog(#"%d",[dishesArray count]);
       if ([dishesArray count]>0) {
           optionFlag=YES;
       }else{
           for (int i=0; i<[tempStr intValue]; i++) {
               DishData *dishData=[[DishData alloc]init];
               dishData.dishTitle=(NSMutableString*)[[tableMenuArray objectAtIndex:indexPath.row] itemName];
               dishData.accompArrayIndex=nil;
               dishData.cookArrayIndex=nil;
               dishData.dishComent=nil;
               dishData.nonMandArray=nil;
               [dishDicArray addObject:dishData];
           }
           [dishDictionary setObject:dishDicArray forKey:dishSelect];
       }
       //[dishesArray release];
       //[dishDicArray release];
       dishSelectRow=indexPath.row;
     //  NSString *dishSelect=[NSString stringWithFormat:#"dish%d",indexPath.row];
       
       [isSelected removeAllObjects];
       [isSelectedAccompArray removeAllObjects];
       [isSelectedCookArray removeAllObjects];
       [self defaultDataArray];
       [accompmentTblView reloadData];
       [cookingTblView reloadData];
       [nonMandTblView reloadData];
       [nonMandtSelectOptionArray removeAllObjects];
       optionsView.hidden=NO;
   }
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//If possible make a singleton instance here of "dishDictionary" may solve your issue of crashing (Rather diclare it at the class level)
//if(!dishDictionary)
dishDictionary=[[NSMutableDictionary alloc]init];
..........
//Replace this line :
NSMutableArray *dishDicArray=[[NSMutableArray alloc]init];
to
NSMutableArray *dishesArray=[[NSMutableArray alloc]initWithArray:[dishDictionary objectForKey:dishSelect]];
and remove
dishesArray=[dishDictionary objectForKey:dishSelect];
..........
//may will not crash than try this
}