Monday, July 29, 2013

Core Data in IOS (for Beginners)

Core Data in IOS (for Beginners)

Introduction
Core Data is a schema-driven object graph management and persistence framework
Fundamentally, Core Data helps you to save model objects (in the sense of the model-view-controller design pattern) to a file and get them back again.






Core Data is available on iOS 3.0 and later.


--------------------------------------------------------------------------------------
What i am going to do is...


Step 1

Create a ARC Project ....



Click the ARC also



Step 2

Click the "CoreDataTute.xdatamodeled"




Click Add Entity icon and type Student(Table name)


 Click the plus Sign to add Attribute





Step 3
click this icon to see the table



Step 4

Add new class for your Project



Step 5

Type this code in your  .h class (which you add new class in above)
#import <UIKit/UIKit.h>

@interface InsertDataViewController : UIViewController
{
 IBOutlet UITextField *nameField;

}
-(IBAction)save;
-(IBAction)Fetch;


@end

----------------------------------------------------------------

Step 6

Type this code in your  .m class (which you add new class in above)
Import the "AppDelegate.h"  .m class to your class
-----------------------------------------------------------------------------------------------------------------------

#import "InsertDataViewController.h"
#import "AppDelegate.h"

@interface InsertDataViewController ()

@end

@implementation InsertDataViewController

- (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 from its nib.
}


-(IBAction)save{

AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];

//Entity for table name : Team
NSEntityDescription *entity=[NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:appDelegate.managedObjectContext];

//set value for the column name
[entity setValue:nameField.text forKey:@"name"];

NSError *error;


//its returns true when values inserted in database succesfuly otherwise false
BOOL isSaved= [appDelegate.managedObjectContext save:&error]; 
NSLog(@"Successfully Saved : flags @%d",isSaved);

}


-(IBAction)Fetch{

AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];

//create Entity object for Table : Student
NSEntityDescription *entity=[NSEntityDescription entityForName:@"Student" inManagedObjectContext:appDelegate.managedObjectContext];

//create fetch request
NSFetchRequest *fetchRqst=[[NSFetchRequest alloc]init];
[fetchRqst setEntity:entity];

//Get all rows in mutable array
NSMutableArray *array=[[appDelegate.managedObjectContext executeFetchRequest:fetchRqst error:nil]mutableCopy];

//Core data return each row as managed object so we can access rows values through key value pair
for(NSManagedObject *obj in array)
{
   NSLog(@"SLIIT Student Names: %@\n",[obj valueForKey:@"name"]);
}

}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

-----------------------------------------------------------------------------------

Step 7

Design the following Ui and Connect those Method like this.....







Step 8

 go to the AppDelegate.m class and set Above viewController(in my case it is  InsertDataViewController)  as a Root View Controller
 to do that import view controller Header file to the AppDelegate.h class 
and change the code of   

"- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions"  method in AppDelegate.h

#import "InsertDataViewController.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
InsertDataViewController *rootViewController=
[[InsertDataViewController alloc] initWithNibName:@"InsertDataViewController" bundle:nil];
[self.window setRootViewController:rootViewController];

self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}

--------------------------------------------------------------------------------------------------------------

Step 9

Run Your App & insert some data and Click the fetch button ....



  • After click Save Button



this mean your successfully  added .................!

  • After Click Fetch Button




Monday, July 1, 2013

Local Notification in IOS

Local Notification in IOS



Step 1
Design this
  
Step 2
add this code in "viewController.h" 


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    IBOutlet UITextField *message;
}

@property (nonatomic, retain) UITextField *message;

-(IBAction) btnSet:(id) sender;
-(IBAction) btnCancelAll:(id) sender;

@end


Step 3
type this code in "viewController.m" 


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize message;

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

-(IBAction) btnSet:(id) sender
{
    
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    
    //---set the notification to go off in 10 seconds time---
    localNotification.fireDate =
    [[NSDate alloc] initWithTimeIntervalSinceNow:10];
    
    //---the message to display for the alert---
    localNotification.alertBody = message.text;
    
    localNotification.applicationIconBadgeNumber = 1;
   
    //---uses the default sound---
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    
    //---title for the button to display---
    localNotification.alertAction = @"View Details";
    
   //---schedule the notification---
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    [localNotification release];
}

-(IBAction) btnCancelAll:(id) sender
{
    //---cancel all notifications---
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


Step 4

add this method in "AppDelegate.m" 


- (void) application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
    
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Inside application Receive Local Notification "
                          message:notification.alertBody
                          delegate:self
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil];
    application.applicationIconBadgeNumber = 0;
    
    [alert show];
    [alert release];
     
}

Step 5




Step 6

Run Your app

Type Something 

After 10 Second

          


























Click the Notification


























Friday, June 28, 2013

How to Add a Search Bar in Table View

How to Add a Search Bar in Table View


Step1
     create a Project  by using" single view  application"



Step2
       Add  this code to ViewController.h file

//
//  ViewController.h
//  SearchBAr2
//
//  Created by Dhanushka Adrian on 6/26/13.
//  Copyright (c) 2013 Adrian. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITabBarDelegate,UITableViewDataSource,UISearchBarDelegate>
{
    IBOutlet UITableView *tableView;
    IBOutlet UISearchBar *searchBAr;
    NSArray *allItem;
    NSMutableArray *displayItems;
    
}

@end

Step 3
    add UISearchBar & UITableView





















Step 4

















connect searchbar


Step 5
In ViewController change code like this


//
//  ViewController.h
//  SearchBAr2
//
//  Created by Dhanushka Adrian on 6/26/13.
//  Copyright (c) 2013 Adrian. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    allItem=[[NSArray alloc] initWithObjects:@"Supun",@"Adrian",@"Dhanushka",@"Kasun",@"Damith",@"Chamitha",@"Thilina",@"Asela",@"Shanika",@"Chandrakantha",@"Tharidu", nil];
    displayItems=[[NSMutableArray alloc] initWithArray:allItem];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHidden:) name:UIKeyboardWillHideNotification object:nil];
// Do any additional setup after loading the view, typically from a nib.
}

//
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return  1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  [displayItems count];
    
}


-(UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //static NSString *simpleTableIdentifier = @"SimpleTableItem";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    cell.textLabel.text = [displayItems objectAtIndex:indexPath.row];
    return cell;
}


                      

//when user type text in search bar ........(textChange)

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
    if([searchText length] == 0)//if there nothig in search field
    {
        [displayItems removeAllObjects];
        [displayItems addObjectsFromArray:allItem];
    }
    else
    {
       [displayItems removeAllObjects];
        
        for(NSString *string in allItem)//every single item in allItem array
        {
            NSRange r=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];//where it is
            
           
            if(r.location!=NSNotFound)
            {
                [displayItems addObject:string];
            }
        }
       
        

    
    }
    
    [tableView reloadData];
}

-(void)keyboardHidden:(NSNotification *)note
{
      [tableView reloadData];
}

-(void)keyboardShown:(NSNotification *)note{
    
    CGRect keyboardFrame;
    
    [[[note userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey]getValue:&keyboardFrame];
    

}
//handle the search button click in keyboard------------
- (void)searchBarSearchButtonClicked:(UISearchBar *)asearchBar
{
    
    [asearchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


Step 6

Run the App