Objective C - Pass a value from UIViewController t

2019-08-17 23:26发布

问题:

First of all, let me say that I am new to Objective C.

I'm basically trying to pass the originalPriceOnGraph variable from ViewController (UIViewController) to the original variable from GraphView (UIView). However, I keep getting 0.00 when I try and display original. I don't get what exactly is the problem. Here's some of my code:

GraphView.h

@interface GraphView : UIView
@property (nonatomic) double original;
@end

GraphView.m

@implementation GraphView
@synthesize original;

- (id)initWithFrame:(CGRect)frame
{
   //some code here
}
- (void)drawRect:(CGRect)rect;
{
   NSLog(@"%.2f", original);
   //some more code here
}
@end

ViewController.m

@interface OtherViewController ()
@end
@implementation OtherViewController
@synthesize originalPriceOnGraph;
@synthesize graph;

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

   originalPriceOnGraph = 20.00;

   graph = [[GraphView alloc] init];
   graph.original = originalPriceOnGraph;
}

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

ViewController.h

@interface OtherViewController : UIViewController
@property (strong, nonatomic) GraphView *graph;
@property (nonatomic) double originalPriceOnGraph;
@end

Thank you in advance!

EDIT: I was able to solve this by creating an IBOutlet between the OtherViewController and GraphView. I also got rid of the alloc init statement for GraphView in ViewController.m. Thank you all for your suggestions!

回答1:

Are you sure the GraphView's drawRect: method isn't getting called before you set its 'original' property?

If so, try initializing any instance of a GraphView with a default value for original.

In GraphView.h:

-(id)initWithOriginal:(double)original;

In GraphView.m:

-(id)initWithOriginal:(double)original
{
    self = [super init];
    if (self) {
        [self setOriginal:original];
    }
    return self;
}

In ViewController.m:

-(void)viewDidLoad
{
    [super viewDidLoad];

    originalPriceOnGraph = 20.00;

    [self setGraph:[[GraphView alloc] initWithOriginal:originalPriceOnGraph]];
}


回答2:

use :

self.graph = [[GraphView alloc] init];

self.graph.original = originalPriceOnGraph;