在其他方法的init方法后,NSString属性是否为null?
我有一个小问题。 这是我的源代码:
.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它为空。
所以,你可以看到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)
我非常感谢你能帮助我,我不知道那里有什么问题。
它看起来像你正在实例化两个不同的“ TBNoteViewController
”实例。
你正在编程(在代码中),这就是你如何让“ noteKey
”属性正确显示。
然后第二个创建是因为你从XIB文件中加载它,这就是为什么“ viewDidLoad:
”被调用。
在摆脱了代码调用的额外代码之后,创建一个通过XIB文件创建的插座,然后您可以设置属性,并且应该全部设置。
链接地址: http://www.djcxy.com/p/90353.html上一篇: NSString property gets null after init method in other methods?