Friday, 28 February 2014

Save data into NsuserDefault using objective C


- (IBAction)SaveUsingNsuserDefault:(id)sender
{

NSMutableArray* mutableArry   =  [[NSMutableArray allocinit];

    NSMutableDictionary *array = [[NSMutableDictionary alloc]init];
    [array setObject:txtName.text forKey:@"name"];
    [array setObject:txtCity.text forKey:@"city"];
    [array setObject:txtPass.text forKey:@"pass"];
    
    NSMutableArray *studentArray;
    NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
    NSArray *previousSavedArray = [currentDefaults objectForKey:@"saveStudents"];
    if (previousSavedArray != nil)
        studentArray = [[NSMutableArray alloc] initWithArray:previousSavedArray];
    else
        studentArray = [[NSMutableArray alloc] init];
    
    NSMutableArray* arrStudentDetails = [currentDefaults objectForKey:@"saveStudents"];

    
    mutableArry = arrStudentDetails;
    
    if([[txtName.text checkNullFromString:txtName.text] isEqualToString:@""]|| [[txtCity.text checkNullFromString:txtCity.text] isEqualToString:@""]|| [[txtPass.text checkNullFromString:txtPass.text] isEqualToString:@""])
    {
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Required" message:@"Empty Field not allowed !!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
        if([mutableArry count]>0)
        {
            [self.tblEmpDetails reloadData];
        }
        return;
    }
   
        int j = [previousSavedArray count];
        for (int i = 0; j>i; i++) 
        {
            NSString* strName = [[previousSavedArray objectAtIndex:i]valueForKey:@"name"];
            if([strName isEqualToString:txtName.text])
            {
                
                UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Exist" message:@"Record allready exist !!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                return;
            }
        }
    
    [studentArray addObject:array];
    [currentDefaults setObject:studentArray forKey:@"saveStudents"];
    [currentDefaults synchronize];
    
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Saved successfully !!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    
     arrStudentDetails = [currentDefaults  objectForKey:@"saveStudents"];

    mutableArry = arrStudentDetails;
    if([mutableArry count]>0)
    {
        [self.tblEmpDetails reloadData];
    }


}

No comments:

Post a Comment