从另一个类访问一个属性 [英] Accessing a property from another class

查看:73
本文介绍了从另一个类访问一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个应用程序,用户在文本字段输入一个数字,按下按钮后,另一个视图显示该输入的结果。

Im trying to build an app where the user inputs a number at a textfield and after pressing the button another view shows up with the result of that input.

每个用户输入的数字应在第二个视图中返回不同的值。由于数据量很大,我创建了一个自定义类来存储所有这些数据。现在我不知道如何从这个自定义类的字段中访问文本。你能帮助我吗?

Each number that the user inputs should return a different value at the second View. Since the data will be huge, I created a custom Class to store all this data. Now im not sure how can I access the text from the field at this custom Class. Can you help me?

问题在于:

int intVal = [[ViewController.fieldLabel text] intValue];

整个代码:

MainView.m

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

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

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    ResultViewController *resultController = (ResultViewController *)segue.destinationViewController;
    resultController.segueLabel = [self number];
}



- (IBAction)showResultView:(id)sender {
}

@end

Library.h

#import <Foundation/Foundation.h>

@interface LibraryData : NSObject

- (NSString *)number;

@end

Library.m

#import "LibraryData.h"
#import "ViewController.h"

@implementation LibraryData

- (NSString *)number {
    int intVal = [[ViewController.fieldLabel text] intValue];
    if (intVal < 5000) {
        return @"Poor!";
    }
    else {
        return @"Rich!";
    }
}


@end


推荐答案

由于这种情况下的库就像你的模型一样,因此ViewController负责设置和提取数据。该库不会(也不应该)知道有关ViewController类的任何信息。这是您遇到的问题的一个很好的解决方案:

Since Library in this case is acting like your model it is your ViewController's responsibility to set and pull the data from it. The library does not (and should not) know anything about the ViewController class. This is a good solution to the problem you are facing:

首先,您需要在ViewController中使用一个库实例:

So first, you will need a Library instance in your ViewController:

@interface ViewController ()
// Make sure you import library above
@property (strong, nonatomic) Library *library;
@end

创建实际实例:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.library = [Library new];
}

然后在按钮单击中,您应该访问视图的文本字段并将其设置为开启图书馆:

Then in your button click you should access your view's text field and set it on the library:

- (IBAction)showResultView:(id)sender {
    self.library.number = [[self.fieldLabel text] intValue];
}

这篇关于从另一个类访问一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆