I am trying to count the words in Pages document (the doc format is RTF) using the scripting bridge. (I can do it using NSApplescript but I would rather not have all the applescript-aware duct tape in my code)
When I perform this task using applescript (and NSAppleScript APIs) I can do this very simply (and successfully):
on wordCount(appName,docName)
local mydoc
local wordcount
tell application appName
set mydoc to document docName
set wordcount to count of words of mydoc
log "wordcount = " & wordcount
return wordcount
end tell
end wordCount
However when I try the equivalent using the scripting bridge all my objects seem to have null contents. My code is as follows:
+ (NSUInteger) wordCountForApp: (SBApplication*) sbApp docNamed: (NSString*) docName
{
PagesApplication *pages = (PagesApplication*)sbApp;
PagesDocument *doc = [[pages documents] objectWithName:docName];
PagesText *text = [doc bodyText];
SBElementArray *words = [text words];
NSUInteger wc = [words count];
NSLog(@"Pages word count = %ul", (unsigned int) wc);
return wc; // wc comes back as zero always ... grrrr
}
I have verified that I am running this stuff on the main thread (and that equivalent code works against TextEdit). Any ideas as to what is going on/how to work around?
Thanks for having read this far….
So the problem was that I was asking for a document named “something.rtf” that I had just opened in Pages. But when Pages opens “something.rtf” it names it “something”. And then when you ask for document named “something.rtf” it does not return nil because the document does not exist by that name. Instead, it returns a PagesDocument named “something.rtf” which has no valid contents: a NIL document. Which I guess I just was too stupid to recognize when I submitted to SO.
I have since checked other apps and this seems to be normal applescript behavior when you ask for a document by name (to get back a “valid object” containing a NIL document) oh well.