3

私はまだAppleが提供するチュートリアルである「MySecondiOSApp」を改善しようとしています。これは、何が起こるべきかについての解説が追加されたストーリーボードの写真です。

解説付きのストーリーボードの詳細

完了ボタン(ステップ3)をクリックすると、実際の画面がメインメニュー(3.a)に戻り、完成したBirdSightingObjectがBirdMasterViewController(3.b)のリストに追加されます。同時に追加できるオブジェクトは1つだけであり、さまざまなクラスからのアクセスがはるかに簡単になるため、シングルトンを使用できると考えました。

チュートリアルでは、データ処理用のクラス「BirdSighting」がすでに提供されています。これはおそらくシングルトンとして使用できます。しかし、私はOOPとデザインパターンの初心者レベルの知識しか持っていないので、これを使用できるかどうか、または既存のクラスを参照して独自に作成する必要があるかどうかはわかりません。

そして第二に:私は最終的にリストにオブジェクトを保存するためにメソッドのにアクセスBirdMasterViewControllerする方法を少しも考えていません。(IBAction)done

注:次のソースコードは、Apple、Incによって部分的に提供されています。チュートリアルの完全なコードリストを表示するには、これを参照してください。著作権侵害は意図されていません。

BirdSighting.h

@interface BirdSighting : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *location;
@property (nonatomic, strong) NSDate *date;

- (id)initWithName:(NSString *)name location:(NSString *)location date:(NSDate *)date;
- (id)initWithNameOnly:(NSString *)name date:(NSDate *)date;

@end

BirdSighting.m

#import "BirdSighting.h"

@implementation BirdSighting

- (id)initWithName:(NSString *)name location:(NSString *)location date:(NSDate *)date
{
    self = [super init];
    if (self)
    {
        _name = name;
        _location = location;
        _date = date;
        return self;
    }
    return nil;
}

-(id)initWithNameOnly:(NSString *)name date:(NSDate *)date
{
    self = [super init];
    if (self)
    {
        _name = name;
        _date = date;
        return self;
    }
    return nil;
}

@end

(IBAction)doneメソッド、でMainMenuViewController.m

- (IBAction)done:(UIStoryboardSegue *)segue
{
    if ([[segue identifier] isEqualToString:@"ReturnInput"])
    {
        AddLocationToSighting *addController = [segue sourceViewController];
        if (addController.birdSighting)
        {
            [self.dataController addBirdSightingWithSighting:addController.birdSighting];
            [[self tableView] reloadData];
        }
        [self dismissViewControllerAnimated:YES completion:NULL];
    }
}

概要:

  • May I transform BirdSighting into a singleton? And if so, what is missing? (No need to code it out for me, I hope I can do it on my own if you provide a hint.)
  • How do I save the object in the BirdMasterViewController? I have no idea how to access the noninvolved ViewController in (IBAction)done.
4

1 に答える 1

4

May I transform BirdSighting into a singleton?

No.

BirdSighting is a model object, not a collection, and certainly not a variable that needs to be globally accessible. You can, however, make a singleton Bird Sighting Manager, that controls a list of bird sightings and can add, remove, or serialize them as appropriate. Although, bear in mind that singletons create global state, which is always a bad thing.

How do I save the object in the BirdMasterViewController?

これもまた、上で提案したシングルトンに戻ります。また、追加コントローラーとメインリストビューの間の何らかの形式の委任を提案しますが、それはすべての中間ビューコントローラーでの課題になる可能性があります。通知でも機能します(infoパラメーターに新しい目撃情報が含まれている場合)。

于 2013-03-27T08:51:25.897 に答える