星期三, 1月 11, 2012

ios iphone/ipad Dev 學習筆記 (A-05) 在不同 View 之間傳遞資料,使用 singleton pattern

環境:Xcode 4.2 + iOS SDK 5
目標:
  • 延續前例
  • 建立 singleton class 作為全域變數的儲存空間
  • 在 HomeView 增加一個 TextField 供輸入文字,離開 HomeView 前往 SecondView 之前,將 TextField 中的文字存到 singleton class 中
  • 當 View 切換到 SecondView,從 singleton class 中將剛剛存進去的資料讀出來,放到 Label 

說明:

  • 建立 singleton class:
  BPGblShareData.h
  
  #import <Foundation/Foundation.h>

  @interface BPGblShareData : NSObject{

  }
  
  @property (nonatomic, retain) NSString * textFieldText;

    +(id) sharedManager;

  @end


  BPGblShareData.m

  #import "BPGblShareData.h"

  @implementation BPGblShareData

  @synthesize textFieldText;

  #pragma  mark Singleton Methods

  +(id) sharedManager{

      // 網路上大部份的人這樣做
      //@synchronized(self){
      //    if(bpGblShareData == nil)
      //        bpGblShareData = [[self alloc] init];
      //}

      // 提醒到,Apple 的文件建議這樣做
      static dispatch_once_t pred;
      static BPGblShareData * bpGblShareData;
    
      dispatch_once(&pred , ^{
          bpGblShareData = [[BPGblShareData alloc] init]; 
      });

      return bpGblShareData;
  }

  -(id)init{
      if(self = [super init]){
          textFieldText = @"";

      }
      return self;
  }

  -(void) dealloc{
      //用不到,放著
  }

  @end


  • 編輯 HomeViewController.h 增加這一行
  @property (nonatomic, strong) UITextView * textbox;
  • 編輯 HomeViewController.m
  #import "HomeViewController.h"
  #import "SecondViewController.h"
  #import "BPGblShareData.h"

  @implementation HomeViewController

  @synthesize label;
  @synthesize button;
  @synthesize textbox;

  SecondViewController * secondViewController;

  - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  {
      self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
      if (self) {
         // Custom initialization
      }
      return self;
  }

  - (void)didReceiveMemoryWarning
  {
      // Releases the view if it doesn't have a superview.
      [super didReceiveMemoryWarning];
    
      // Release any cached data, images, etc that aren't in use.
  }

  #pragma mark - View lifecycle

  /*
  // Implement loadView to create a view hierarchy programmatically, without using a nib.
  - (void)loadView
  {
  }
  */

  - (void)viewDidLoad
  {
      CGRect frame = CGRectMake(20, 10, 280, 50);
      label = [[UILabel alloc] initWithFrame:frame];
      label.textAlignment = UITextAlignmentCenter;
      label.font = [UIFont fontWithName:@"Verdana" size:20];
      label.text = @"Hello World !!!";
    
      // add first button
      frame = CGRectMake(20, 160, 280, 50);
      button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
      button.frame = frame;
      button.backgroundColor = [UIColor clearColor];
      [button setTitleColor:[UIColor blackColor  forState:UIControlStateNormal];
      [button setTitle:@"這是按鈕" forState:UIControlStateNormal];

      // action handler for button
      [button addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];

      //add textview
      frame = CGRectMake(20, 70, 280, 50);
      textbox = [[UITextView alloc] initWithFrame:frame];
      [textbox setBackgroundColor:[UIColor lightGrayColor]];
      [textbox setFont:[UIFont fontWithName:@"arial" size:30.0]];
    
      //add subviews 
      [self.view addSubview:label];
    
      [self.view addSubview:button];

      [self.view addSubview:textbox];
    
      [super viewDidLoad];    

  }

  - (void)viewDidUnload
  {
      [super viewDidUnload];
      // Release any retained subviews of the main view.
      // e.g. self.myOutlet = nil;
  }

    (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
  {
      // Return YES for supported orientations
      return (interfaceOrientation == UIInterfaceOrientationPortrait);
  }

  -(void) btnClicked:(id) sender{
      NSLog(@"button clicked !!");
      // 將 TextView 裡面的資料存到全域變數區裡    
      BPGblShareData * gblSharedData = [BPGblShareData sharedManager];
      gblSharedData.textFieldText = self.textbox.text;
    
      secondViewController = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
    
      [UIView beginAnimations:@"flipping view" context:nil];
      [UIView setAnimationDuration:1];
      [UIView setAnimationCurve:UIViewAnimationOptionTransitionNone];
      [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view.superview cache:NO];
    
      [self.view.superview addSubview:secondViewController.view];

      //要把自己移除,否則會留下『殘影』
      [self.view removeFromSuperview];
    
      [UIView commitAnimations];        

  }
  @end

  • 編輯 SecondViewController.m
  #import "SecondViewController.h"
  #import "HomeViewController.h"
  #import "BPGblShareData.h"

  @implementation SecondViewController
  @synthesize labelOn2ndView = _labelOn2ndView;
  @synthesize btnOn2ndView = _btnOn2ndView;

  HomeViewController *homeViewController;

  - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  {
      self = [super   initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
      if (self) {
          // Custom initialization
      }
      return self;
  }


  - (void)didReceiveMemoryWarning
  {
      // Releases the view if it doesn't have a superview.
      [super didReceiveMemoryWarning];
    
      // Release any cached data, images, etc that aren't in use.
  }

  #pragma mark - View lifecycle

  /*
  // Implement loadView to create a view hierarchy programmatically, without using a nib.
  - (void)loadView
  {
  }
  */

  // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
  - (void)viewDidLoad
  {
          //=========================================================================
          //這是我的練習
        
          //加一個 Label View
          CGRect frame = CGRectMake(20, 10, 280, 50);
          self.labelOn2ndView = [[UILabel alloc] initWithFrame:frame];
          self.labelOn2ndView.textAlignment = UITextAlignmentCenter;
          self.labelOn2ndView.font = [UIFont fontWithName:@"Verdana" size:20];
          //取得 HomeViewController 傳出來的資料
          BPGblShareData * gblSharedData = [BPGblShareData sharedManager];
          self.labelOn2ndView.text = gblSharedData.textFieldText;
        
          //加入第一個 ButtonView
          frame = CGRectMake(20, 160, 280, 50);
          self.btnOn2ndView = [UIButton buttonWithType:UIButtonTypeRoundedRect];
          self.btnOn2ndView.frame = frame;
          [self.btnOn2ndView setTitle:@"回到 Hello World" forState:UIControlStateNormal];
          self.btnOn2ndView.backgroundColor = [UIColor clearColor];
    
          //讓按鈕有生命,當按鈕被按到就呼叫 btn2Pressed 這個動作
          [self.btnOn2ndView addTarget:self action:@selector(btn2Pressed:) forControlEvents:UIControlEventTouchUpInside];
    
          [self.view addSubview:self.labelOn2ndView];
          [self.view addSubview:self.btnOn2ndView];    
    
          //=========================================================================

          [super viewDidLoad];
  }

  - (void)viewDidUnload
  {
      [super viewDidUnload];
      // Release any retained subviews of the main view.
      // e.g. self.myOutlet = nil;
  }

  - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
  {
      // Return YES for supported orientations
      return (interfaceOrientation == UIInterfaceOrientationPortrait);
  }

  -(void)btn2Pressed:(id)sender{
    NSLog(@"2ndView btn Pressed");
      homeViewController = [[HomeViewController alloc] initWithNibName:nil bundle:nil];
    
      [UIView beginAnimations:@"flipping view" context:nil];
      [UIView beginAnimations:@"switch view" context:nil];
      [UIView setAnimationDuration:1];
      [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
      [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view.superview cache:NO];
    
      [self.view.superview addSubview:homeViewController.view];
    
      //要把自己移除,否則會留下『殘影』
      [self.view removeFromSuperview];
    
      [UIView commitAnimations];        

  }

  @end






沒有留言: