1

我有我的类,其中包含我的数据数据我在名为ViewController 的第一个视图中创建了我的对象 我将创建其他视图控制器,我想在我的 ViewController 中创建的对象“man1”中读取和写入数据。我怎样才能做到这一点 ?非常感谢。

到目前为止,这是我的代码:

数据.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

数据.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

视图控制器.h

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

@interface ViewController : UIViewController
{
    int testint;

}


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


@end

视图控制器.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
4

1 回答 1

0

Your approach is not going to work, because you allocate a new instance of Data each time a view is loaded, and because each view controller gets its own Data object.

One approach to fixing this is making your Data class a singleton. Your view controllers will be accessing a single instance of Data, ensuring that the information is shared among the view controllers:

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
于 2013-11-04T15:01:02.823 回答