iphone - 在 View Controller 之间传递/共享数据的方式有多少

标签 iphone objective-c xcode xcode4.2 data-sharing

我是 IOS 和 Objective-C 以及整个 MVC 范例的新手,我坚持以下内容。

我正在开发(副本)联系人应用程序,该应用程序也可以在 iPhone 中作为内置应用程序使用。我想通过另一个 View Controller 传递数据并且数据是 pass (null) :(。

我的问题是,如何将数据从一个 View 传输到另一个 View ?

最佳答案

正如您得到的大多数答案一样,在一个 Controller 和另一个 Controller 之间传递数据只是意味着将变量从一个 Controller 分配给另一个 Controller 。 如果您有一个 Controller 列出您的联系人,另一个 Controller 显示联系人详细信息,并且流程从列表开始并在选择联系人后转到详细信息,您可以分配联系人变量(可以是数组中的对象显示在你的列表中)并在显示这个之前将它分配给详细 View Controller 。

- (void)goToDetailViewControllerForContact:(Contact *)c
{
    ContactDetailViewController *detailVC = [[[ContactDetailViewController alloc] init] autorelease];
    detailVC.contact = c;
    [self.navigationController pushViewController:c animated:YES];
    //[self presentModalViewController:detailVC animated:YES]; //in case you don't have a navigation controller
}

另一方面,如果你想从细节 Controller 插入一个新的联系人到列表 Controller ,我想最好的方法是将列表 Controller 作为委托(delegate)分配给细节 Controller ,所以当一个联系人是添加了代表收到通知并按预期行事(将联系人插入数组并重新加载 TableView ?)。

@protocol ContactDelegate <NSObject>
- (void)contactWasCreated:(Contact *)c;
// - (void)contactWasDeleted:(Contact *)c; //may be useful too...
@end

@interface ContactListViewController : UIViewController <ContactDelegate>
@property (nonatomic, retain) NSArray *contacts;
...
@end

@implementation ContactListViewController
@synthesize contacts;
...

- (void)goToDetailViewControllerForContact:(Contact *)c
{
    ContactDetailViewController *detailVC = [[[ContactDetailViewController alloc] init] autorelease];
    detailVC.contact = c;
    detailVC.delegate = self;
    [self.navigationController pushViewController:c animated:YES];
    //[self presentModalViewController:detailVC animated:YES]; //in case you don't have a navigation controller
    }

- (void)contactWasCreated:(Contact *)c
{
    self.contacts = [self.contacts arrayByAddingObject:c]; //I'm not sure this is the correct method signature...
    [self reloadContacts]; //may be [self.tableView reloadData];

}

...
@end


@interface ContactDetailViewController : UIViewController

@property (nonatomic, assign) id<ContactDelegate> delegate;
...
@end


@implementation ContactDetailViewController
@synthesize delegate; //remember to don't release it on dealloc as it is an assigned property
...

- (void)createContactAction
{
    Contact *c = [[[Contact alloc] init] autorelease];
    [c configure];
    [self.delegate contactWasCreated:c];
}

...
@end

关于iphone - 在 View Controller 之间传递/共享数据的方式有多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9016680/

相关文章:

iphone - 如何通过手势识别器检测圆形手势?

iphone - 在 NSString 中出现一个字符

iphone - 如何避免调用位置更新了三次

ios - 我如何使用 block 来更改 iOS 中的执行上下文?

objective-c - SpriteKit 缺少线性变换矩阵

ios - UITests Xcode7 : How to adjust date picker with multiply pickers?

iphone - 我可以发送没有声音的本地通知吗?

objective-c - 使用 UITableView 和条件时字体颜色设置不正确

ios - 构建应用程序时找不到 Cocoapods header

ios - XCode强制换行