Objective-C: Refreshing FrontmostApplication - objective-c

I wrote this little program which is supposed to print the current frontmost application twice, with a 3-second break in between.
void printFrontmostApp() {
NSRunningApplication *frontmostApplication = [NSWorkspace sharedWorkspace].frontmostApplication;
NSLog(#"%#",frontmostApplication);
}
int main(int argc, const char * argv[]) {
#autoreleasepool {
printFrontmostApp();
sleep(3);
printFrontmostApp();
}
return 0;
}
When I ran this program, I realised that frontmostApplication is not refreshed when it is called the second time. I found the solution here. But I still have two questions:
1) I want to know why the frontmostApplication is not updated.
2) How do I force it to refresh every time I call it? I don't want to receive a notification every time the frontmost application deactivates, because it is a little inefficient for my purposes.
Edit:
Just to be crystal clear, let's suppose the time now is 10:00:00. I call printFrontmostApp, and it prints "Xcode" to the console, because Xcode is the current frontmost app. Then the program sleeps for 3 seconds. At 10:00:01, I opened another app, say TextEdit. At 10:00:03, my program calls printFrontmostApp for the second time. I expect it to print "TextEdit", which is the current frontmost application. But it prints "Xcode" instead. I can't understand this behaviour.
Can someone please explain what happens at 10:00:03? The function seems to "remember" the value of frontmostApplication at 10:00:00 and retains it when it is called the second time. I thought that any memory will be released once it goes out of scope, so why is this happening?
And how do I get my program to get the frontmost app at 10:00:03? I can get the frontmost app at 10:00:00, I should be able to do the same 3 seconds later right?

The documentation for -[NSWorkspace runningApplications] — not the method you're using, but related — says:
Similar to the NSRunningApplication class’s properties, this property will only change when the main run loop is run in a common mode. Instead of polling, use key-value observing to be notified of changes to this array property.
From the NSRunningApplication documentation:
Properties that vary over time are inherently race-prone. For example, a hidden app may unhide itself at any time. To ameliorate this, properties persist until the next turn of the main run loop in a common mode. For example, if you repeatedly poll an unhidden app for its hidden property without allowing the run loop to run, it will continue to return NO, even if the app hides, until the next turn of the run loop.
It's a near certainty that the same principle applies to -frontmostApplication even though the documentation doesn't say so explicitly. You will never get different results by polling without allowing the run loop to run.

For 1) the answer is the same described in the question you have linked: You have to observe this notification, that tells you when a new application was activated:
NSWorkspaceDidActivateApplicationNotification
About 2) You have different observers for activation and deactivation like:
NSWorkspaceDidDeactivateApplicationNotification
So your are not going to observe notifications that you are not registered, please take a look at NSWorkspace Notifications for a comprehensive list.
Otherwise, please define your question about refreshing/polling (that I think it's not a good idea anyways).

Related

Cannot inspect Self in method while debugging

I have a method on one of my ViewController's that is called by one of its view's and delivered some value. It then sends out a message to a manager object with some information about the VC's state.
- (void)elementXChangedWithValue:(float)value {
ParameterManager * pMan = [ParameterManager sharedInstance];
[pMan updateParameter:self.elementX.parameter value:value];
}
In debugging, it was important for me to inspect what the .SomeElement.parameter state was so I could know what was getting lost in translation by the time I get to my ParameterManager.
Unfortunately, although Self is definitely non-nil and accessible the debugger shows scant information about the class making quick and practical glancing of the value difficult. (i will sometimes invoke "po" command in the debugger command line, however).
Not sure if it helps but this project is running heavy with the Objective-C/Swift interoperability although the ViewController is a fully Objective-C class.
Here is an image of what I am getting in the debugger. The drop-down arrow shows nothing but empty.
The debugger isn't perfect and sometimes you just cant see what is in certain areas, such as self. What does always work is NSLog's placed in code though, so if all else fails, add one of those in at the right place to print out the object you wish to know about.
The debugger may show more info after you make it execute these commands:
expr #import UIKit;
expr #import Foundation;
This loads the whole UIKit and Foundation symbols in the debugger at runtime, you only need to execute it once per debug session.
You can automate this with a user-defined breakpoint that'll be triggered every time your application starts in the debugger.
Source : http://furbo.org/2015/05/11/an-import-ant-change-in-xcode/

How to change variables between scripts in UnityScript?

I made a game have two objects in the hierarchy panel. One called GameScreen and another called Clock I set up. Each has its own script attached. GameScreen uses game.js and the other uses clock.js.
When I win the game a popup box appears and says, "You've won!" This is caused by the game.js script. However, the clock.js is still running, so my clock is still counting down. When the time is up the clock.js makes a popup box saying, "you lose!"
This causes for a "you win" screen to pop up when you win and then later a you lose screen to appear. As you can probably guess, this is super annoying. If there was a way I could change variables in one script from another,, I could get the clock to stop when you won or I could get the game to stop when the time ran out.
Is there some way to do this??
For example here are two javascript files one on clock and the other on GameScreen . I want the first one to change the variable changeMe in the second to two.
1.js:
function start(){
}
2.js:
var changeMe:int;
When you win the game, you can change clock's variable from game.js this way:
GameObject.Find("Clock").GetComponent("clock.js").variable_name = new_value;
, where [variable_name] and [new_value] obviously depend on your project. variable_name has to be an exposed variable.
You can simply use SendMessage() it will make you able to call a function from another object easily.Basically you need to write a function to destroy the clock after wining the game,let's say your function is called destroyClock so you should add that to your game.js script:
gameobject.Find("here goes the name of your clock obj").sendMessage("destroyClock")

EXC_BAD_ACCESS on animationForKey:

I'm trying to use a recent feature of the Scintilla component, which provides OSX-like text-highlighting effect (the yellow animated bouncing box), and I'm stuck with an error that pops up intermittently :
EXC_BAD_ACCESS
pointing to this particular line :
if (layerFindIndicator!=nil)
if ([layerFindIndicator animationForKey:#"animateFound"])
[layerFindIndicator removeAnimationForKey:#"animateFound"];
(the ifs are mine; just in case I caught the object layerFindIndicator being nil, or deallocated or whatever... Unfortunately, it doesn't help...)
layerFindIndicator is seemingly a subclass of CAGradientLayer. (You may see the full code for layerFindIndicator, here).
Since, I'm an absolute newbie to Quartz Core, could please give me any hint as to HOW this could be debugged?
Since, I'm an absolute newbie to Quartz Core, could please give me any hint as to HOW this could be debugged?
This doesn't have anything to do with QuartzCore specifically (at least, I hope not)—it's general this-object-has-been-killed-before-its-time-how-do-I-find-the-killer stuff.
In Xcode:
Edit your current scheme.
For the Profile action, set it to use the Debug build configuration.
Dismiss that and then hit the Profile command.
Xcode will build for that action and then launch Instruments.
Instruments will prompt you to choose a template; you want the Zombies template. Once you've chosen it, Instruments will create a trace document and run your application. Switch to your application (if it isn't already frontmost), then do whatever causes the crash.
If the crash really is a dead-object crash, Zombies will reveal it. You'll get a flag in Instruments's timeline saying something like “message sent to zombie object 0xd3c2b1a0”, and your program will probably exit shortly thereafter.
In that flag is a tiny little button that looks like this: ➲ except it'll be gray. Click on it.
That takes you to the history of that object (actually of that address, including any previous objects or other allocations that have started at that address). Show your Extended Detail Pane (the one that appears on the right showing a stack trace), then scroll down to the end and then move backward (upward) step by step through time, looking at releases and autoreleases, looking for the one that isn't balancing out the object's allocation or a retain.
The solution will probably involve one or more of:
Changing a property to be strong or weak rather than assign/unsafe_unretained
Adding a property where you previously did not strongly own an object
Rearchitecting some things, if it's not clear which of the above you need to do or if either one of them seems like a filthy hack
Switching to ARC to get weak properties and __weak instance variables (both of which get set to nil automatically when the referenced object dies) and to get local variables being implicitly initialized to nil
But it'll depend on what you find in Instruments. And, of course, there's the chance that your problem—the bad access—isn't a dead object at all and all of the above will not help you.
Try this:
if (layerFindIndicator!=nil){
if ([layerFindIndicator animationForKey:#"animateFound"]){
[layerFindIndicator removeAnimationForKey:#"animateFound"];
}
}
Also check to see if it is released else were.
EDIT:
Another thing I found was you didn't have an white space in the if. Your code should now look like this:
if (layerFindIndicator != nil){
if ([layerFindIndicator animationForKey:#"animateFound"]){
[layerFindIndicator removeAnimationForKey:#"animateFound"];
}
}

Cocoa: int main function

I'm curious, what role does the int main function play in a Cocoa program? Virtually all of the sample code I've been looking at has only the following code in main.m:
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
What exactly is this doing, and where does the program actually start stepping through commands? It seems my conceptions need readjustment.
Since a Cocoa project starts like any other, the entry point for the Operating system is main. However the Cocoa Architecture is constructed to actually start the processing of your program from NSApplicationMain, which is responsible for loading the initial window from your application and starting up the Events loop used to process GUI events.
Apple has a very in depth discussion on this under the Cocoa Fundamentals Guide : The Core Application Architecture on Mac OS X
If you want to learn how control passes from "launch this" to the main() function, the execve man page has the details. You would also want to read about dyld. main() is a part of the Unix standard. Every single program that you can run effectively has a main().
As others have mentioned, NSApplicationMain passes control to Cocoa. The documentation is quite specific as to what it does.
One interesting note, NSApplicationMain doesn't actually every return. That is, if you were to separate the call to NSApplicationMain from the return in your main function and put code in between, that code would never be executed.
main() is the entry point for your program.
When you run your program that is the first function called. Your program ends when you exit that function.
Also note that this does not come from Objective-C. This is simple C.
Have a look at
Wikipedia's page on it
Value returned from main is returned by the process to operating system when the process is done.
Shell stores the value returned by last process and you can get it back with $? :
> ls
a b c
> echo $?
0
> ls x
x: No such file or directory
> echo $?
1
ls is an application like anything else.
You can use the return value to chain multiple processes together using shell script or anything else that can execute a process and check for return value.
I'm wondering where the code begins
executing (like why does an NSView
subclass execute and draw without me
explicitly calling it?) and if I'm not
supposed to stick my main loop in int
main() where does it go?
In an xcode project you have a main.m file that contains the 'int main' function. You won't actually find the code that calls the NSView draw explicitly, this code is hidden deep within an iPhone or Mac OS X framework. Just know that there is an event loop hidden deep within your 'int main' that checks for changes so that it knows when to update your view. You don't need to know where this event loop is, it's not useful information since you can override methods or create and assign delegates that can do things when this happens.
To get a better answer, you'll need to explain what you mean by a 'main loop' that you wanted to put inside the 'int main' function.
It's just weird to me coming off a
little experience in C++. It looks
unnatural that the main function would
be so empty.
You can encapsulate a billion lines of code into one function and put it into 'int main'. Don't be deceived by a main only having a few lines, that is done on purpose. Good programming teaches us to keep code in specific containers so that it is well organized. Apple chose to make the "real" launch point of their iPhone apps in this single line of code inside the main.m file:
int retVal = UIApplicationMain(argc, argv, nil, #"SillyAppDelegate");
From that one piece of code, an app's delegate is launched and won't return control to the main function until it is done.

How do I pause a function in c or objective-c on mac without using sleep()

Hi I would like to pause the execution of a function in an cocoa project. I dont want to use sleep() because the function needs to resume after user interaction. I also want to avoid doing this with multiple calls to sleep.
Thanks for your responses. Ok I started the code while waiting for some answers. I then realized that sleep or pause would not be usefull to me because it freeses my whole program. I think I might have to do some threading. Here is the situation:
I have a program that uses coreplot. I also use it to debug and develop algorithms so I do lots of plots while the data is being processed (ie in the midfle of the code but I need the flexibility to put it anywhaere so I cant separate my function). I was able to do this with NSRunAlertPanel but having a message box like that doesnt make it very presentable and I cant do much with the main window while an alert is open.
I hope I am not too confusing with my explanation but if I am ill try to one line it here:
I would like to interact with my cocoa interface while one of my functions is stopped in the middle of what it is doing.
Its sounds to me like you're looking for -NSRunLoop runUntilDate:
Apple's Docs: runUntilDate
This code will cause the execution within your method to pause but still let other events like timers and user input occur:
while ( functionShouldPause )
{
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
}
Switching functionShouldPause back to false will allow the rest of the method to execute.
It seems more like you are interested in reacting to user events rather than "pausing" the function. You would probably want to put the code that you want to execute into another function that is called as a result of the user's actions.
In C you can use the pause() function in <unistd.h>. This causes the calling program to suspend until it receives a signal, at which point the pause call will return and your program will continue (or call a signal handler; depending on what signal was received).
So it sounds like you want to break the function into two parts; the bit that happens before the sleep and the bit that happens afterward. Before going to sleep, register for a notification that calls the "after" code, and can be triggered by the UI (by an IBAction connected to whatever UI element). Now instead of calling sleep(), run the run loop for the period you want to go to sleep for, then after that has returned post the "after" notification. In the "after" code, remove the object as an observer for that notification. Now, whichever happens first - the time runs out or the user interrupts you - you get to run the "after" code.
Isn't there a clock or timer function? When your button is pressed start running a loop like timeTillAction = 10 and do a loop of timeTillAction = timeTillAction - 1 until it reaches 0 then run whatever code after the 10 seconds.
Sorry if this isn't well explained.