2013-11-04 39 views
1

我有我的CLASSE其中包含我的數據數據 我創造了我的目標,我叫的ViewController 我將創建人viewControllers第一視圖和我想讀與寫之間的對象數據在我的ViewController中創建的對象「man1」中。 我該怎麼做? 非常感謝。IOS傳遞超過2個視圖控制器

這是到目前爲止我的代碼:

Data.H

#import <Foundation/Foundation.h> 

@interface Data : NSObject 
{ 
    NSString *name; 
    int age; 
    NSString *city; 
} 
- (id)initWithName:(NSString *)aName ; 

- (NSString*) name; 
- (int) age; 
- (NSString*) city; 

//- (void) setPrenom:(NSString*) prenom; 
- (void) setName:(NSString*) newName; 
- (void) setAge:(int) newAge; 
- (void) setCity:(NSString*) newCity; 

@end 

Data.m

#import "Data.h" 

@implementation Data 


- (id)initWithName:(NSString *)aName 
{ 
    if ((self = [super init])) 

    { 
    self.name = aName; 

} 
    return self; 

} 


//getter 
- (NSString*) name 
{ 
    return name; 
} 

- (int) age{ 
    return age; 

} 

- (NSString*) city{ 
    return city; 
} 


//setter 
- (void) setName:(NSString*)newName 
{ 
    name = newName; 
} 
- (void) setAge:(int) newAge 
{ 
    age = newAge; 
} 
- (void) setCity:(NSString *)newCity 
{ 
    city = newCity; 
} 



@end 

ViewController.h

#import <UIKit/UIKit.h> 
#import "Data.h" 

@interface ViewController : UIViewController 
{ 
    int testint; 

} 


@property (readwrite) Data *man1; 
@property (weak, nonatomic) IBOutlet UILabel *labelAff; 


@end 

ViewController.m

#import "ViewController.h" 
#import "Data.h" 

@interface ViewController() 

@end 

@implementation ViewController 
@synthesize man1 = _man1; 

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


    NSString * name1 = @"Bob"; 
    _man1 = [[Data alloc]initWithName:name1 ]; 
    NSLog(@" %@ ", _man1.name); 

    [_man1 setAge:29]; 
    NSLog(@" %d ", _man1.age); 


    [_man1 setCity:@"Tapei"]; 
    _labelAff.text = [_man1 city]; 

} 



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

@end 

回答

0

你的做法是行不通的,因爲你每一個視圖被加載時分配的Data一個新實例,因爲每個視圖控制器都有自己的Data對象。

解決此問題的一種方法是making your Data class a singleton。您的視圖控制器將要訪問的Data單個實例,確保信息的視圖控制器之間共享:

Data.h

@interface Data : NSObject 
{ 
    NSString *name; 
    int age; 
    NSString *city; 
} 
- (id)initWithName:(NSString *)aName ; 

- (NSString*) name; 
- (int) age; 
- (NSString*) city; 

- (void) setName:(NSString*) newName; 
- (void) setAge:(int) newAge; 
- (void) setCity:(NSString*) newCity; 
+(Data*)instance; 
@end 

Data.m

@implementation Data 

-(id)initWithName:(NSString *)aName { 
    if(self=[super init]) { 
     ... 
    } 
    return self; 
} 

+(Data*)instance { 
    static dispatch_once_t once; 
    static Data *sharedInstance; 
    dispatch_once(&once, ^{ 
     sharedInstance = [[self alloc] initWithName: ...]; 
    }); 
    return sharedInstance; 
} 
@end 
+0

非常感謝你,我會先解決這個問題 –

+0

@MaxPuis你試過這個嗎?它有用嗎? – dasblinkenlight

+0

我爲我的對象使用單例,但我仍然不知道如何在視圖控制器之間共享數據 –

相關問題