我正在阅读 Apple 提供的教程并尝试改进 "My Second iOS App" ,用于观鸟的应用程序。 (有一个 MasterView,其中列出了所有输入的目击事件。如果您单击其中一个,您将被定向到该目击事件的 DetailView。您可以添加一个目击事件并被要求输入名称和位置。)
我想分离输入鸟类名称和位置的 View 。
所以我有两个 View (一个用于输入名称,一个用于输入位置)和一个我要存储的对象。
在文件 BirdSighting.m
中,我添加了以下方法
-(id)initWithNameOnly:(NSString *)name date:(NSDate *)date
{
self = [super init];
if (self) {
_name = name;
_date = date;
return self;
}
return nil;
}
和
-(id)setLocation:(NSString *)location
{
if (self) {
_location = location;
return self;
}
return nil;
}
在 AddSightingNameViewController.m
中,我实现了以下代码
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"ToLocation"])
{
if ([self.birdNameInput.text length])
{
BirdSighting *sighting;
NSDate *today = [NSDate date];
sighting = [[BirdSighting alloc] initWithNameOnly:self.birdNameInput.text date:today];
self.birdSighting = sighting;
}
}
}
用于输入名称的 View 通过推送转至位置 View 。其他方面没有太大变化。
现在如何将第一个 View 中生成的对象传递给第二个 View ? 我如何在 AddSightingLocationViewController 中调用此特定对象的
?我必须定义不同的属性吗?我如何在输入位置后最终在 MasterView 中显示正确数据的对象?setLocation
方法.m
由于这段代码还没有工作,我什至不知道它是否工作,我想做什么。因此,如果这是糟糕的代码,请保持温和。
最佳答案
这是我一直在使用的方法:
首先,您需要在目标 View Controller 中添加一个属性,以保存您要传递的对象:
@property (strong, nonatomic) BirdSighting *newSighting;
然后将第一个 View Controller 中的 prepareForSegue 方法更改为以下内容:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"ToLocation"])
{
if ([self.birdNameInput.text length])
{
BirdSighting *sighting;
NSDate *today = [NSDate date];
sighting = [[BirdSighting alloc] initWithNameOnly:self.birdNameInput.text date:today];
self.birdSighting = sighting;
// Get destination view
YourDestinationViewController *vc = (YourDestinationViewController *)segue.destinationViewController;
// Pass birdSighting object to your destination view controller
[vc setNewSighting:self.birdSighting];
}
}
}
我想我最初是从这个 question 得到这个方法的
还值得注意的是,BirdSighting 类在它的 .h 文件中有一个位置 @property,您会注意到 .m 文件中的 @synthesize 行。
@synthesize 指令自动为您创建访问器方法:
@property (nonatomic, copy) NSString *location;
自动生成以下方法(但在文件中不可见):
- (NSString *)location;
- (void)setValue:(NSString *)location;
因此,您无需使用以下方法覆盖 BirdSighting.m 文件中位置的 setter 方法:
-(id)setLocation:(NSString *)location
如果删除该方法(注意它应该返回 void 而不是 id),您现在应该能够通过以下方式访问 BirdSighting 对象中的位置变量:
// In this example we are accessing a BirdSighting @property (hence the use of self.sighting)
// @property (strong, nonatomic) BirdSighting *sighting;
// Getter - returns (NSString *)location of the BirdSighting object
[self.sighting location];
// Setter - sets the location property of the BirdSighting object to 'newLocation'
[self.sighting setLocation:newLocation];
希望这能为您解决一些问题!
关于iphone - 你的第二个 iOS 应用 : Edit one object in two different views,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15199673/