How to access NSDocument object from another object held in NSMutableArray?

女生的网名这么多〃 提交于 2019-12-11 16:25:32

问题


This is really an extension of How to show calculated values in NSTableView?

The problem:

I have an NSDocument class that contains two properties: text (NSString) and phrases (NSMutableArray of NSObjects with NSString in them). In the Doc NIB file I have a TextView (to display phrases) with two columns. First column is bound to an ArrayController and displays NSString. That works ok. I want to count the number of NSString occurrences in text and display that in the second column.

What I tried:

Define a static var in my NSObject that would point to a TextView. Once the NIB is loaded it would set this static var to a TextView that contains the text string.

This works OK if I open a single window. But if I try opening multiple windows, the static var would get updated with the new instances of TextView (from other windows). Obviously this breaks everything.

Question:

How do I access text from each of the NSObject? In other words, the object diagram is NSDocument --(contains one)--> NSMutableArray --(contains multiple)--> NSObject, so how do I get to NSDocument from NSObject?


回答1:


Instead of an array of strings, use an array of dictionaries:

    NSDictionary *entry = [NSDictionary dictionaryWithObjectsAndKeys:
                                          thePhrase, @"phrase",
                                          theCount, @"count",
                                          nil];
    [theArray addObject:entry];

Bind to arrangedObjects.phrase and arrangedObjects.count.

Alternatively, you could create a Phrase class which contains the phrase, a reference to the document, and code to calculate the count.



来源:https://stackoverflow.com/questions/7704345/how-to-access-nsdocument-object-from-another-object-held-in-nsmutablearray

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!