0

我有一个有两个 NSString 数据成员的类

头文件

@interface WebSiteFavorites : NSObject

@property (strong, nonatomic) NSString *titleName;
@property (strong, nonatomic) NSString *url;`

- (id) initWithTitleName: (NSString *)titleName url: (NSString *)url;

@end

我有一个使用此类作为其数据源的 TVC,并且我在 appDelegate 中对我的类的一些实例进行了硬编码,以填充可以工作的 TV。在电视上,我有一个添加按钮,其中包含到 VC 的模态转换。在这个视图控制器中,我有两个文本字段,用户在其中输入名称和 url,然后我使用协议和委托来更新 TVC(我不太明白)。我的问题是,在文本字段中输入所需信息后,我的类实例为空。

这是我的代码

标题 @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 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

在 IBAction 方法之后,我使用了断点并且收藏夹为空。我也有一些关于协议和代表的问题,只是为了理解。我为我的协议创建了一个单独的头文件,我的 TVC 符合协议,在我的 VC 中我创建了委托,您可以在我发布的代码中看到它。在我的 TVC 中,我已经实现了协议中的功能。这是正确的顺序吗?

4

1 回答 1

1

您必须实例化favorites. 如果不实例化对象,则不会保存您分配给它们的值。

所以你必须做...

favorites=[[WebSiteFavorites alloc] init];

或者当您有另一种方法initWithTitleName:url:时,请使用它来实例化。

希望这可以帮助!

于 2012-12-14T19:34:15.893 回答