[英]Your Second iOS App: Edit one object in two different views
我正在閱讀Apple提供的教程,並試圖改進“我的第二個iOS應用程序” ,這是一個鳥類觀察應用程序。 (有一個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;
}
}
}
輸入名稱的視圖帶有推送到位置視圖的segue。 其他方面沒有太大變化。
現在我如何將第一個視圖中生成的對象傳遞給第二個? 如何在AddSightingLocationViewController.m
對此特定對象調用setLocation
方法? 我必須定義不同的屬性嗎? 在進入該位置后,如何最終使用正確的數據在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];
}
}
}
我想我最初從這個問題得到了這個方法
值得注意的是,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];
希望這能為你解決一些問題!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.