I have a class with two NSString data members
Header file
@interface WebSiteFavorites : NSObject
@property (strong, nonatomic) NSString *titleName;
@property (strong, nonatomic) NSString *url;`
- (id) initWithTitleName: (NSString *)titleName url: (NSString *)url;
@end
I have a TVC that uses this class as its data source, and I have hard coded some instances of my class in the appDelegate to populate the TV which works. From the TV i have a add button with a modal transition to a VC. In this view controller I have two text fields where the user enters a name and a url and then I using protocols and delegate to update the TVC (which i don’t quite understand). My problem is that after the entering the required info in the text fields my class instance is null.
Here is my code for this
Header
@interface WebSiteFavoritesAddFavoritesViewController : UIViewController
@property (strong, nonatomic) WebSiteFavorites *favorites;
@property (weak, nonatomic) IBOutlet UITextField *titleTextField;
@property (weak, nonatomic) IBOutlet UITextField *urlTextField;
@property (strong) id<WebSiteFavoritesDelegate> delegate;
- (IBAction)titleTextFieldChanged;
- (IBAction)urlTextFieldChanged;
- (IBAction)doneButtonTapped:(id)sender;
- (IBAction)cancelButtonTapped:(id)sender;
@end
Implementation
@implementation WebSiteFavoritesAddFavoritesViewController
@synthesize favorites = _favorites;
@synthesize urlTextField = _urlTextField;
@synthesize titleTextField = _titleTextField;
- (IBAction)titleTextFieldChanged
{
self.favorites.titleName = self.titleTextField.text;
}
- (IBAction)urlTextFieldChanged
{
self.favorites.url = self.urlTextField.text;
}
- (IBAction)doneButtonTapped:(id)sender
{
[self.delegate newFavoriteAdded:self.favorites];
[self dismissModalViewControllerAnimated:YES];
}
- (IBAction)cancelButtonTapped:(id)sender
{
[self dismissModalViewControllerAnimated:YES];
}
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
@end
After the IBAction methods i have used break points and favorites is null.
Also I have some questions about protocols and delegates just for understanding. I have created a separate header file for my protocol, my TVC conforms to the protocol, in my VC i have created the delegate which you can see in my posted code. In my TVC i have implemented the function from my protocol. Is this the proper sequence?
You must instantiate
favorites. Without instantiating objects don’t hold the values you assign to them.So you must do…
or as you have another method
initWithTitleName:url:, do use that to instantiate.Hope this helps!