0

私はiOS開発を始めたばかりで、NSMutableArrayのアイデアを知りたいです。具体的には、あるVCから別のViewControllerに属するNSMutableArrayにNSString値を渡したいと思います。また、NSMutableArrayがそのビューにUITableViewを設定するようにします。これを行う方法はありますか?たとえば、ユーザーが1番目のビュー内からトリガーするこのアクションがあります

- (IBAction)addToFav:(id)sender {  
}

そして、NSStringmyBookStringの値を2番目のビューのNSMutableArray配列に渡したいと思います。- (void)insertObject:(id)anObject atIndex:(NSUInteger)indexタスクはかなり単純ですが、Appleのリファレンスドキュメントに記載されているこのメソッドの外でNSMutableArrayに値を渡せない理由を完全に理解することはできません。前もって感謝します!

編集:私のビューは、UITabBarとUINavigationControllerに同時に属する異なるVCです

4

2 に答える 2

3

You need a communication between two controllers. There are several solutions. Pick one of the following. I recommend delegate.

From http://www.hollance.com/

When you have two objects A and B, say two view controllers, that you want to make talk to each other, you can choose from the following options:

NSNotificationCenter.

  • This is anonymous one-to-many communication. Object A posts a notification to the NSNotificationCenter, which then distributes it to any other objects listening for that notification, including Object B. A and B do not have to know anything about each other, so this is a very loose coupling. Maybe a little too loose…</li>

KVO (Key-Value Observing).

  • One object observes the properties of another. This is a very tight coupling, because Object B is now peeking directly into Object A. The advantage of KVO is that Object A doesn’t have to be aware of this at all, and therefore does not need to send out any notifications — the KVO mechanism takes care of this behind the scenes.

Direct pointers.

  • Object A has a pointer to Object B and directly sends it messages when something of interest happens. This is the tightest coupling possible because A and B cannot function without each other. In the case of view controllers you generally want to avoid this.

Delegates

  • Object B is a delegate of Object A. In this scenario, Object A does not know anything about Object B. It just knows that some object performs the role of its delegate and it will happily send messages to that delegate, but it doesn’t know — or care — that this is Object B. The delegate pattern is often the preferred way to communicate between view controllers, but it takes some work to set up.

Blocks.

  • Essentially the same approach as delegates, except that Object B now gives Object A one or more blocks (closures) to be executed when certain events take place. There is no formal delegate protocol and the only thing that Object A sees of Object B is the blocks it is given.
于 2012-07-26T20:11:17.560 に答える
1

NSMutableArrayはまさにそれであり、標準の可変配列実装です。他の言語/フレームワークで期待されるすべての機能を備えています。ドキュメント

配列に要素を追加する方法の問題は何ですか?[array addObject:object]尻尾に追加してもかまわない場合もできます。

残りの質問に答えるために、あるコントローラーから別のコントローラーにデータを転送する方法はたくさんあります。ナビゲーションはどのように設定されていますか?UITabBarController、またはUINavigationControllerを使用していますか?ビューは互いにどのように関連していますか?それらがネストされている場合は、データを相互に直接渡すことができます。そうでない場合は、アプリデリゲートなどを使用してデータを保持し、データを渡すことができます。

于 2012-07-26T20:04:10.960 に答える