在其他方法的init方法之后,NSString属性是否为空?

时间:2014-02-13 22:21:34

标签: ios objective-c properties nsstring viewdidload

我有点问题。这是我的源代码:

.h:

#import <UIKit/UIKit.h>

@interface TBNoteViewController : UIViewController <UITextViewDelegate>
@property (nonatomic, copy) NSString *noteKey;
- (IBAction)dismissKeyboard:(id)sender;
- (id)initWithNoteIndex:(int)index;
@end

.m:

#import "TBNoteViewController.h"
#import "PSPDFTextView.h"
#include <tgmath.h>

@interface TBNoteViewController ()
{
CGRect _keyboardRect;
BOOL _keyboardVisible;
}

@property (nonatomic, strong) UIBarButtonItem *rightBarButton;
@property (nonatomic, strong) PSPDFTextView *textView;

@end

@implementation TBNoteViewController
@synthesize noteKey;

- (id)initWithNoteIndex:(int)index
{
self = [super init];

if (self) {
    NSMutableArray *data = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults   standardUserDefaults] objectForKey:@"Notes"] copyItems:YES];
    self.noteKey = [NSString stringWithFormat:@"%@", [data objectAtIndex:index]];

    NSLog(@"1: %@", self.noteKey);
}

return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad
{

NSLog(@"2: %@", self.noteKey);

// Register notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];

_rightBarButton = [self.navigationItem rightBarButtonItem];

self.navigationItem.rightBarButtonItem = nil;

PSPDFTextView *textView = [[PSPDFTextView alloc] initWithFrame:self.view.bounds];
textView.delegate = self;
textView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
textView.font = [UIFont systemFontOfSize:17.f];

[self.view addSubview:textView];

self.textView = textView;

[self.textView setTextContainerInset:UIEdgeInsetsMake(5, 12, 5, 12)];
self.textView.alwaysBounceVertical = YES;
self.textView.keyboardAppearance = UIKeyboardAppearanceDark;

textView.text = self.noteKey;

[super viewDidLoad];
// Do any additional setup after loading the view.
}

所以我的问题是属性noteKey有一个字符串,但在viewDidLoad中它是null。

所以,你可以看到NSLogs,输出就是(只是复制了):

2014-02-13 23:07:21.197 TaskBeater [3205:70b] 1:Hoho。

2014-02-13 23:07:21.199 TaskBeater [3205:70b] 2:(null)

如果你能帮助我,我将非常感激,我不知道那里有什么问题。

1 个答案:

答案 0 :(得分:3)

在我看来,你正在实例化两个不同的“TBNoteViewController”实例。

您正在以编程方式(在代码中)执行一项操作,这就是让“noteKey”属性正确显示的方式。

然后创建第二个,因为您从XIB文件加载它,这就是调用“viewDidLoad:”的原因。

在删除了您在代码中调用的额外内容之后,创建一个通过XIB文件创建的插座,然后您可以设置该属性,并且您应该全部设置。