简体   繁体   中英

Obj-C object is null

In my iOS app, I have forward declaration of "Person" class in my AddPersonViewController class as follows.

@protocol PersonAddDelegate;
@class Person;
@interface AddPersonViewController : UIViewController

@property (nonatomic, unsafe_unretained) id <PersonAddDelegate> delegate;
@property (nonatomic, strong) Person * person;

@end

@protocol PersonAddDelegate <NSObject>

- (void)AddPersonViewController:(AddPersonViewController *)addPersonViewController didAddPerson:(Person *)person;

@end

But when I try to call person object from the code as follows, I noticed that person is nil even though self.nameTextField.text returns string as expected:

self.person.personname = self.nameTextField.text;

I guess that it is about initializing 'person' but I am not sure of it. Any ideas about the problem and solution? Thank you in advance

With @property get you a backing iVar _person , and the person getter method and setPerson setter method, but you do not get a Person object. It is nil by default and design. If you want it to be non-nil, you should initialize it in the class's init method.

@implementation AddPersonViewController
-(id)init {
    if ( self = [super init] ) {
        _person = [[Person alloc] init];
    }
    return self;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM