分配给模型类中的属性的值在视图/控制器类中消失

时间:2012-08-02 06:41:56

标签: objective-c ios5 xcode4.3

在我的模型类发送变量stringToDisplay之前,NSLog向​​我显示它有一个值。但是当我尝试在我的ViewController中使用它时,我只得到(null)。关于我做错了什么的想法?

(好消息是,在研究这个问题时,我在理解模型和控制器如何相互关联方面取得了一些突破。我仍然是一个完整的新手,但我感觉不像我做了。)

以下是我认为的相关代码:

CalculatorBrain.h

#import <Foundation/Foundation.h>

@interface CalculatorBrain : NSObject
@property (nonatomic) NSMutableString *stringToAdd;
@property (nonatomic,strong) NSString *stringForDisplay;

- (double)performOperation:(NSString *)operation withArray:(NSMutableArray *)particularStackYouNeedToPopOff;

CalculatorBrain.m

@implementation CalculatorBrain
@synthesize stringToAdd = _stringToAdd;
@synthesize stringForDisplay = _stringForDisplay;
@synthesize whatHappenedSinceLastClear = _whatHappenedSinceLastClear;

- (double)performOperation:(NSString *)operation withArray:(NSMutableArray *)particularStackYouNeedToPopOff
{
<long code that I think doesn't matter because this NSLog produces exactly what I want it to:>
NSLog(@"%@",stringForDisplay);
return result;
}

CalculatorViewController.h

#import <UIKit/UIKit.h>

@interface CalculatorViewController : UIViewController
@property (nonatomic) NSArray *arrayOfDictionaries;
@property (nonatomic) NSDictionary *dictionary;
@property (weak, nonatomic) IBOutlet UILabel *variablesUsed;
@property (nonatomic, strong) NSString *operation;

@end

CalculatorViewController.m

#import "CalculatorViewController.h"
#import "CalculatorBrain.h"

@interface CalculatorViewController ()
@property (nonatomic,strong) CalculatorBrain *brain;
@end

@implementation CalculatorViewController
@synthesize display = _display;
@synthesize history = _history;
@synthesize brain = _brain;
@synthesize operation = _operation;


- (IBAction)operationPressed:(UIButton *)sender 
{
NSString *otherString=[self.brain stringForDisplay];
if (self.userIsEnteringNumber) [self enterPressed];
NSString *operation = sender.currentTitle;
double result = [self.brain performOperation:operation withArray:[self.brain whatHappenedSinceLastClear]];
self.display.text = [NSString stringWithFormat:@"%g",result];
self.history.text = otherString;
NSLog(@"%@",otherString);
}

最后一行代码中的NSLog给了我(null)

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

也许我错过了一些东西,但你的属性是在CalculatorBrain的类扩展中声明的,所以CalculatorBrain.m之外的人都不知道这个属性。

因此,如果您想将此属性公开给其他对象,则必须在CalculatorBrain.h中声明它。

答案 1 :(得分:2)

哦 - 您的属性whatHappenedSinceLastClear声明未向其他导入CalculatorBrain.h的类公开,因为您将属性声明放在​​interface .m扩展名中文件,其他类不会看到。

要使其可公开访问,请将@property的{​​{1}}行移至whatHappenedSinceLastClear,而不是CalculatorBrain.h文件。