我正在研究Apple提供的教程,并尝试改进"My Second iOS App"(用于发现鸟的应用程序)。
(有一个MasterView,其中列出了所有输入的瞄准点。如果单击一个,将直接转到该瞄准点的DetailView。您可以添加一个瞄准点,并要求输入名称和位置。)
我想分开输入鸟类名称和位置的视图。
因此,我有两个视图(一个用于输入名称,一个用于输入位置)和一个要存储的对象。
在文件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;
}
}
}
输入名称的视图通过推键引导到位置视图。没有太多改变。
现在如何将第一个视图中生成的对象传递给第二个视图? 以及如何在
setLocation
中对此特定对象调用AddSightingLocationViewController.m
方法?我必须定义不同的属性吗?输入位置后,如何最终在MasterView中以正确的数据显示对象?由于此代码尚无法正常工作,我什至不知道它是否正在工作,我想做什么。因此,如果这是糟糕的代码,请保持谨慎。
最佳答案
这是我一直在使用的方法:
首先,您需要在目标视图控制器中添加一个属性,以保存要传递的对象:
@property (strong, nonatomic) BirdSighting *newSighting;
然后将第一个视图控制器中的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 not id),则现在应该可以通过以下方式访问BirdSighting对象中的location变量:
// 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];
希望这为您清除了一些麻烦!