Setting the text of an NSTextField programmaticall

2019-09-08 23:34发布

问题:

I have a GUI built on IB (Xcode 4).
It has a Static Text field connected to an NSTextField. After reading the information from an XML file it's supposed to change the text to whatever it is coming from the XML

the .h is as follow:

IBOutlet NSTextField * DataBaseLocation;

the .m

NSMutableArray* DBLoc = [[NSMutableArray alloc] initWithCapacity:1];
NSXMLElement* root  = [doc rootElement];
NSArray* DBarray = [root nodesForXPath:@"//DataBaseLocation" error:nil];
for(NSXMLElement* xmlElement in DBarray)
    [DBLoc addObject:[xmlElement stringValue]];

NSString * DBLocationString = [DBLoc objectAtIndex:0];
[DataBaseLocation setStringValue:DBLocationString];

NSLog(@"DBLoc: %@", DBLoc);

The NSLog shows that DBLoc has the correct string, yet the Text Field is empty and never gets set.

yes, I checked the connections in IB. Any ideas? thanks!

回答1:

Found the answer.

I needed to initialize the NSXMLDocument with NSXMLDocumentTidyXML like:

NSXMLDocument* doc = [[NSXMLDocument alloc] initWithContentsOfURL: [NSURL fileURLWithPath:input] options:NSXMLDocumentTidyXML error:NULL];


回答2:

You should print out DBLocationString instead of DBLoc to make sure it's not empty or in some corrupted format that can't be passed as a string value and go from there.