我在两个类之间使用委托,以便在有任何更新或需要添加对象时得到通知。第一个类是 UITableViewController 的子类,第二个是 UIViewController 的子类。第一个类有一个加号(addButton)来将对象添加到它的表视图中。第二类是按下添加按钮时第一个导航到的视图。所以在视图控制器类中,我在 .h 文件中添加了一个协议:
@protocol ViewControllerDelegate <NSObject>
- (void) addViewControllerDelegate:(ViewController *)controller didUpdateEvent:(Event *) event;
@end
我添加了一个代表@propety:
@property (weak, nonatomic) id <SSAddViewControllerDelegate> delegate;
在 .m 文件中,在按下保存按钮时触发的 IBAction 方法中添加了以下内容:
[self.delegate addViewControllerDelegate:self didUpdateEvent: event];
现在回到表视图控制器类,在我添加的 .h 文件和 .m 文件中我添加了以下方法:
- (void) addViewControllerDelegate:(ViewController *)controller didUpdatEvent:(Event *)event{
[self saveNewEntry:event];
NSLog(@"DELEGATE");
}
问题:它不工作。虽然我想我做了所有应该做的事情。
注意:我在这里更改了类的名称,所以不,我没有名为 ViewController 的类。saveNewEntry 用于将事件对象添加到我的数组中,并且 nslog 在那里,以便知道它是否确实进入了方法。
//------------------------------------ 更多实际代码---------- ------------------- 第二类(视图控制器).h 和 .m 分别
@class Course;
@class SSAddViewController;
@protocol SSAddViewControllerDelegate;
@interface SSAddViewController : UIViewController <UITextFieldDelegate>
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
@property (weak, nonatomic) id <SSAddViewControllerDelegate> delegate;
@end
@protocol SSAddViewControllerDelegate <NSObject>
- (void) addViewControllerDelegate:(SSAddViewController *)controller didUpdateCourse:(Course *) course;
@end
@class Course;
@class SSAddViewController;
@protocol SSAddViewControllerDelegate;
@interface SSAddViewController : UIViewController <UITextFieldDelegate>
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
@property (weak, nonatomic) id <SSAddViewControllerDelegate> delegate;
@end
@protocol SSAddViewControllerDelegate <NSObject>
- (void) addViewControllerDelegate:(SSAddViewController *)controller didUpdateCourse:(Course *) course;
@end
- (void) saveNewEntry
{
SSAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [appDelegate managedObjectContext];
Course *course = (Course *) [NSEntityDescription insertNewObjectForEntityForName:@"Course" inManagedObjectContext:context];
NSLog(@"YES");
[course setCourseName:self.nameTextField.text];
[course setCourseCredits:[NSNumber numberWithInt:[self.creditstextField.text intValue]]];
[course setCourseChapters:[NSNumber numberWithInt:[self.chaptersTextField.text intValue]]];
if (hasChanges) {
[self.delegate addViewControllerDelegate:self didUpdateCourse:course];
}
}
第一类(表视图).h 和 .m 分别:
@interface SSCoursesViewController : UITableViewController <SSAddViewControllerDelegate>
- (void) addViewControllerDelegate:(SSAddViewController *)controller didUpdateCourse:(Course *)course{
[self saveNewEntry:course];
NSLog(@"DELEGATE");
}