2015-02-09 3 views
0

Я очень новичок в Applescript-ObjC и стараюсь сделать что-то довольно простое. У меня есть это приложение applescript, которое я использовал для преобразования текста в Title Case и ALL CAPS. Приложение отлично работает. Но когда я пытаюсь привести его в Xcode AppDelegate.applescript и присоединить его к кнопкам в пользовательском интерфейсе, ничего не происходит. Я запускал «Build» без ошибок, но он просто ничего не делает, когда я открываю приложение и нажимаю кнопки.Проблема с использованием Applescript в ApplescriptObjc Проект Xcode

Любая помощь была бы принята с благодарностью. Заранее спасибо.

(BTW этот скрипт из http://macscripter.net/viewtopic.php?pid=42284#p42284)

script AppDelegate 
property parent : class "NSObject" 
-- IBOutlets 

on applicationWillFinishLaunching_(aNotification) 
    -- Insert code here to initialize your application before any files are opened 
end applicationWillFinishLaunching_ 


on applicationShouldTerminate_(sender) 
    -- Insert code here to do any housekeeping before your application quits 
    return current application's NSTerminateNow 
end applicationShouldTerminate_ 

############# My Buttons ############# 

-- Title Case -- 

on clickTitleCase_(sender) 
    set someText to the clipboard 

    set newCase to (changeCase of someText to "title") (* "upper", "lower", "sentence", "capitalized" or "title" *) 

    set the clipboard to newCase 
end clickTitleCase_ 

-- All CAPS -- 

on clickALLCAPs_(sender) 
    set someText to the clipboard 

    set newCase to (changeCase of someText to "upper") (* "upper", "lower", "sentence", "capitalized" or "title" *) 

    set the clipboard to newCase 
end clickALLCAPs_ 

############# Text Conversion Handlers ############# 

property lowerStr : "abcdefghijklmnopqrstuvwxyzáàâäãåæçéèêëíìîïñóòôöõōøœúùûüÿ" 
property upperStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÀÂÄÃÅÆÇÉÈÊËÍÌÎÏÑÓÒÔÖÕŌØŒÚÙÛÜŸ" 
property alphaList : lowerStr's characters & reverse of upperStr's characters 
property sentenceBreak : {".", "!", "?"} 
property wordBreak : {space, ASCII character 202, tab} 
property everyBreak : wordBreak & sentenceBreak 
property whiteSpace : wordBreak & {return, ASCII character 10} 
property currList : missing value 
property sentenceModList : {"i", "i'm", "i’m", "i've", "i’ve", "I’ve", "I've", "I’m", "I'm", "I"} (* could be extended to include certain proper nouns, acronyms, etc. *) 
property mixedModList : {"A", "For", "So", "An", "In", "The", "And", "Nor", "To", "At", "Of", "Up", "But", "On", "Yet", "By", "Or", "Usa", "Nasa", "Hiv", "Aids", "Vs", "Pm", "Wef", "Wwf", "Nsx", "NSX", "WWF", "WEF", "PM", "vs", "AIDS", "HIV", "NASA", "USA", "or", "by", "yet", "on", "but", "up", "of", "at", "to", "nor", "and", "the", "in", "an", "so", "for", "a"} 

on textItems from currTxt 
    tell (count currTxt's text items) to if it > 4000 then tell it div 2 to return my (textItems from (currTxt's text 1 thru text item it)) & my (textItems from (currTxt's text from text item (it + 1) to -1)) 
    currTxt's text items 
end textItems 

on initialCap(currTxt) 
    tell currTxt to if (count words) > 0 then tell word 1's character 1 to if it is in lowerStr then 
    set AppleScript's text item delimiters to it 
    tell my (textItems from currTxt) to return beginning & upperStr's character ((count lowerStr's text item 1) + 1) & rest 
end if 
currTxt 
end initialCap 

to capItems from currTxt against breakList 
repeat with currBreak in breakList 
    set text item delimiters to currBreak 
    if (count currTxt's text items) > 1 then 
     set currList to my (textItems from currTxt) 
     repeat with n from 2 to count currList 
      set my currList's item n to initialCap(my currList's item n) 
     end repeat 
     set text item delimiters to currBreak's contents 
     tell my currList to set currTxt to beginning & ({""} & rest) 
    end if 
end repeat 
currTxt 
end capItems 

on modItems from currTxt against modList 
    set currList to modList 
    set currCount to (count modList) div 2 
    repeat with currBreak in everyBreak 
     set text item delimiters to currBreak 
     if (count currTxt's text items) > 1 then repeat with n from 1 to currCount 
     set text item delimiters to my currList's item n & currBreak 
     if (count currTxt's text items) > 1 then 
      set currTxt to textItems from currTxt 
      set text item delimiters to my currList's item -n & currBreak 
      tell currTxt to set currTxt to beginning & ({""} & rest) 
     end if 
    end repeat 
end repeat 
currTxt 
end modItems 

to changeCase of currTxt to caseType 
if (count currTxt's words) is 0 then return currTxt 

ignoring case 
    tell caseType to set {upper_Case, lower_Case, sentence_Case, capitalized_Case, title_Case} to {it is "upper", it is "lower", it is "sentence", it is "capitalized", it is "title"} 
end ignoring 

if not (upper_Case or lower_Case or capitalized_Case or sentence_Case or title_Case) then 
    error "The term \"" & caseType & "\" is not a valid case type option. Please use \"upper\", \"lower\", \"sentence\", \"title\" or \"mixed\"." 
    else if upper_Case then 
    set n to 1 
    else 
    set n to -1 
end if 

considering case 
    set tid to text item delimiters 

    repeat with n from n to n * (count lowerStr) by n 
     set text item delimiters to my alphaList's item n 
     set currTxt to textItems from currTxt 
     set text item delimiters to my alphaList's item -n 
     tell currTxt to set currTxt to beginning & ({""} & rest) 
    end repeat 

    if sentence_Case then 
     set currTxt to initialCap(modItems from (capItems from currTxt against sentenceBreak) against sentenceModList) 
     else if capitalized_Case or title_Case then 
     set currTxt to initialCap(capItems from currTxt against whiteSpace) 
     if title_Case then set currTxt to initialCap(capItems from (modItems from currTxt against mixedModList) against sentenceBreak) 
    end if 

    set text item delimiters to tid 
end considering 
currTxt 
end changeCase 

end script 
+1

Общая рекомендация: Chuck все, что дрянной ASCII-только регистр, изменяющий код и использующий '(stringStithString_ (текущий текст) приложения NSString (theText) в качестве текста' (или 'lowercaseString' /' capitalizedString', если это необходимо). Несмотря на то, что все еще не идеально (случай чрезвычайно сложный для того, чтобы машины были совершенно правильными, так как они ничего не знают о собственных существительных и т. Д.), Использование 'NSString' намного проще и быстрее, поддерживает Unicode и лучше подходит для такого рода вещей, любой любительский код AppleScript когда-либо будет. – foo

+0

Я пробовал этот метод, но я предпочитаю этот скрипт, потому что он сохраняет знаки препинания. I – user3803526

+0

Я не знаю - [NSString uppercaseString] и т. Д., Удаляя пунктуацию. Если бы они это сделали, это было бы серьезной ошибкой. Есть примеры? – foo

ответ

0

Per предложения, приведенный выше участников форума, я был в состоянии использовать NSString uppercaseString, чтобы решить эту проблему:

use AppleScript version "2.4" 
use framework "Foundation" 
use scripting additions 

set aPhrase to "this is 'a' test phrase with 'punctuation'" 
its makeTitleCase(aPhrase) 

on makeTitleCase(stringOfText) 
    set makeLowerCaseList to {"A", "For", "So", "An", "In", "The", "And", "Nor", "To", "At", "Of", "Up", "But", "On", "Yet", "By", "Or"} 
    set theString to current application's NSString's stringWithString:stringOfText 
    set theString to (theString's capitalizedString()) 
    set stringOfText to theString as text 
    set AppleScript's text item delimiters to " " 
    set listOfWords to text items of stringOfText 
    set listOfWords to listOfWords as list 
    repeat with x from 2 to count of listOfWords -- item 2 because per APA Style the first word is capitalized irregardless 
     set targetItem to (item x of listOfWords) 
     set aString to (" " & targetItem & " ") 
     set theWord to words of aString as list 
     repeat with y from 1 to count of makeLowerCaseList 
      set origWord to (item 1 of theWord) as text 
      set compareWord to (item y of makeLowerCaseList) as text 
      if origWord = compareWord then 
       set oneWord to (current application's NSString's stringWithString:(item x of listOfWords)) 
       set item x of listOfWords to (oneWord's lowercaseString) as text 
      end if 
     end repeat 
    end repeat 
    return listOfWords as text 
end makeTitleCase 


on makeALLCAPS(stringOfText) 
    set theString to current application's NSString's stringWithString:stringOfText 
    set theString to (theString's uppercaseString()) 
    set stringOfText to theString as text 
    return stringOfText 
end makeALLCAPS 
+0

Вы можете принять свой собственный ответ .. – markhunte

Смежные вопросы