问题
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