Arguments and selectors - iphone

Is this:
[self showInWindow:window];
what get called after delay by this code:
[self performSelector:#selector(showInWindow:)
withObject:window
afterDelay:delay];
or am I misunderstanding the method?
Edit: the problem I'm having is that the method showInWindow get called after the delay but behaves like [self showInWindow:nil]. Any suggestion?

Yes, that's what gets called. (After the delay, of course.)
The documentation doesn't really explain what it means to "perform the selector", but what it means is exactly what you suspect.
There is one small difference between using performSelector:withObject: type methods and sending the message directly: they only work if the object is actually an object (that is, an id, a pointer to an Objective C object). But window obviously is an object.
(Strictly speaking, this isn't quite true. If you pass something that's the same size as an id or smaller, it will often work. In some cases it won't. In some cases it will work, but is illegal. In some cases, it will work and is legal but Apple strongly recommends against it. There are no cases where it's a good idea—so instead of learning the specific rules, just assume it never works. The only reason to bring this up is that this used to be common practice in Objective C back in the NeXT days, so you may occasionally still see it in other people's today.)
For more information about the performSelector: family, see the NSObject Protocol Reference, and the SO question Using -performSelector: vs. just calling the method. (For information specifically about the afterDelay: variants, see the documentation linked above.)
From the later edit to the question:
the problem I'm having is that the method showInWindow get called after the delay but behaves like [self showInWindow:nil]. Any suggestion?
First, in what way does it "behave like" the parameter is nil? Is the parameter actually nil? (Just log it in the showInWindow: implementation; if you haven't overridden the base implementation, just add an override that logs and calls the base.)
Second, if it actually is nil, was it nil at the time you sent performSelector:withObject:afterDelay:? If so, obviously it'll still be nil when the selector is sent. Also, make sure window really is an id rather than some other type. (Note that if you've got members, properties, globals, and/or locals sharing the name window, it can be confusing which one you're referring to. This is a common source of problems.)
If it's actually not nil when you schedule it, but is nil when it arrives, there are a few ways that could happen, but they're all less likely, and trickier to debug, than these two cases, so let's rule them out first.

Yes, that's what it does... Although keep in mind that it may take longer than the delay to execute. This method basically sets up an NSTimer in the current thread's run loop, so if your thread gets busy doing heavy duty work and the run loop takes longer than your delay to come back, your method will get executed later.

Related

Should IOBufferMemoryDescriptor be released of free'd?

I am looking at the documentation of IOBufferMemoryDescriptor. It says "... Except where noted, you are also responsible for releasing buffers that you allocate.".
IOBufferMemoryDescriptor::free also exists. My questions is: should I use free or release (or maybe both) to do the cleanup?
free() is called automatically when the last handle is dropped using OSSafeReleaseNULL. (This calls release() internally, but it's usually best to use the macro.)
So, never call the free() method directly, you only need to care about it in the context of overriding it in your own subclasses. Always use the reference counting mechanism on OSObject-derived classes.

Retain count of the start from 4 [duplicate]

I would like to know in what situation did you use -retainCount so far, and eventually the problems that can happen using it.
Thanks.
You should never use -retainCount, because it never tells you anything useful. The implementation of the Foundation and AppKit/UIKit frameworks is opaque; you don't know what's being retained, why it's being retained, who's retaining it, when it was retained, and so on.
For example:
You'd think that [NSNumber numberWithInt:1] would have a retainCount of 1. It doesn't. It's 2.
You'd think that #"Foo" would have a retainCount of 1. It doesn't. It's 1152921504606846975.
You'd think that [NSString stringWithString:#"Foo"] would have a retainCount of 1. It doesn't. Again, it's 1152921504606846975.
Basically, since anything can retain an object (and therefore alter its retainCount), and since you don't have the source to most of the code that runs an application, an object's retainCount is meaningless.
If you're trying to track down why an object isn't getting deallocated, use the Leaks tool in Instruments. If you're trying to track down why an object was deallocated too soon, use the Zombies tool in Instruments.
But don't use -retainCount. It's a truly worthless method.
edit
Please everyone go to http://bugreport.apple.com and request that -retainCount be deprecated. The more people that ask for it, the better.
edit #2
As an update,[NSNumber numberWithInt:1] now has a retainCount of 9223372036854775807. If your code was expecting it to be 2, your code has now broken.
NEVER!
Seriously. Just don't do it.
Just follow the Memory Management Guidelines and only release what you alloc, new or copy (or anything you called retain upon originally).
#bbum said it best here on SO, and in even more detail on his blog.
Autoreleased objects are one case where checking -retainCount is uninformative and potentially misleading. The retain count tells you nothing about how many times -autorelease has been called on an object and therefore how many time it will be released when the current autorelease pool drains.
I do find retainCounts very useful when checked using 'Instruments'.
Using the 'allocations' tool, make sure 'Record reference counts' is turned on and you can go into any object and see its retainCount history.
By pairing allocs and releases you can get a good picture of what is going on and often solve those difficult cases where something is not being released.
This has never let me down - including finding bugs in early beta releases of iOS.
Take a look at the Apple documentation on NSObject, it pretty much covers your question:
NSObject retainCount
In short, retainCount is probably useless to you unless you've implemented your own reference counting system (and I can almost guarantee you won't have).
In Apple's own words, retainCount is "typically of no value in debugging memory management issues".
Of course you should never use the retainCount method in your code, since the meaning of its value depends on how many autoreleases have been applied to the object and that is something you cannot predict. However it is very useful for debugging -- especially when you are hunting down memory leaks in code that calls methods of Appkit objects outside of the main event loop -- and it should not be deprecated.
In your effort to make your point you seriously overstated the inscrutable nature of the value. It is true that it is not always a reference count. There are some special values that are used for flags, for example to indicate that an object should never be deallocated. A number like 1152921504606846975 looks very mysterious until you write it in hex and get 0xfffffffffffffff. And 9223372036854775807 is 0x7fffffffffffffff in hex. And it really is not so surprising that someone would choose to use values like these as flags, given that it would take almost 3000 years to get a retainCount as high as the larger number, assuming you incremented the retainCount 100,000,000 times per second.
What problems can you get from using it? All it does is return the retain count of the object. I have never called it and can't think of any reason that I would. I have overridden it in singletons to make sure they aren't deallocated though.
You should not be worrying about memory leaking until your app is up and running and doing something useful.
Once it is, fire up Instruments and use the app and see if memory leaks really happen. In most cases you created an object yourself (thus you own it) and forgot to release it after you were done.
Don't try and optimize your code as you are writing it, your guesses as to what may leak memory or take too long are often wrong when you actually use the app normally.
Do try and write correct code e.g. if you create an object using alloc and such, then make sure you release it properly.
Never use the -retainCount in your code. However if you use, you will never see it returns zero. Think about why. :-)
You should never use it in your code, but it could definitely help when debugging
The examples used in Dave's post are NSNumber and NSStrings...so, if you use some other classes, such as UIViews, I'm sure you will get the correct answer(The retain count depends on the implementation, and it's predictable).

Difference between perform selector in backgorund and detachNewThread

I want to know what is difference between perform selector in backgorund and detachNewThread
They Are identical. as you can see in Documentation section Click Here
performSelectorInBackground:withObject: The effect of calling this method is the same as if you called the detachNewThreadSelector:toTarget:withObject: method of NSThread with the current object, selector, and parameter object as parameters.
performSelectorInBackground:withObject: is easier way rather than NSThread.
However, NSThread can control its priority, stacksize, etc. If you'd like to customize the behavior, I recommend NSThread instead of performSelectorInBackground:withObject:.
I would look at it from a semantic point of view. There is no technical reason to use one or the other.
Use NSThread if you actually "think" of having a thread that "does something"; in particular, it will probably be the most appropiate way of creating a thread if your thread runs some form of event- or messaging loop. In such a case, the "thread object" is really just that; in many cases it's not an "application realm" object with actual application data, as these will be handed over to the thread in some way.
Use the NSObject-based methods if your thread is merely meant to run some single operation in the background. You don't really care about this being a "thread", and the object that you run this on is likely to be the "application realm" object with the data; there's no event- or messageloop to feed it commands from other threads.
Thus, I would base the decision on abstract factors, as in "what looks better in the given context". Having an NSThread "feels" like a more detached entity that is willing to offer services to multiple clients, whereas the NSObject method feels like it's closely attached to the data object that it runs with, and doesn't really deal with anything else unless it's vital to the cause.

What is "super" in Objective-C? ( self != super )?

I've read the question below, and the story SEEMS simple:
What exactly is super in Objective-C?
Yet ...
- (id) init
{
NSLog(#"self=%p, super=%p", self, super);
}
That prints out "self=0xa83dc50, super=0xbfffe8d0". The addresses are NOT THE SAME???!?!?
That second address seems like a "special value" or something. What does it mean?
Thanks to bbum for pointing out that this value is the stack address of a special struct used by the compiler to implement the "super" behavior.
I can call [super init] and the call seems to work, or at least, nothing explodes ... not immediately. Calling [((id)0xbfffe8d0) init] fails hard with EXC_BAD_ACCESS.
Then there is the REALLY WEIRD part.....
I've got a piece of code that for no explainable reason throws a "NSGenericException: collection was mutated while being enumerated" exception. Inside a DIFFERENT object (basically a wrapper that has a pointer to the NSEnumerator), commenting out the call to "[super init]" causes the exception to not happen. If I could, I'd put out a $$$ reward for an answer to THAT mind-bender.
"id sups = (id)0xbfffe8d0" ... that also leads to "collection is modified." ... WTF? Ok, so I'm posting a 2nd question for that bizzariotity ...
I originally came here with one of those "bizarre symtoms" bugs, that turned out to be entirely unrelated (typical for such things): Does casting an address to (id) have side-effects??? Is Address 0xbfffe8d0 special? (fixed: issue was with _NSCallStackArray)
However, the content above the line is still valid, and the response still excellent. Read it if you want to understand ObjC just a little bit deeper.
You are messing with the man behind the curtain and he is punishing you for it... :)
super is a bit of compiler magic, really. When you say [super doSomething], the compiler will emit a call to objc_msgSendSuper() instead of objc_msgSend(). Most of the time -- there are some special cases.
In general, you should treat super as only a target for method calls. It should never be stored anywhere and should never be considered anything but that target expression for messaging.
In fact, uses of super that involve storage should likely be flagged by the compiler.
In terms of your bug, that sounds an awful lot like there is either corruption of memory, an over-release, and/or concurrency going on. You'll need to provide more code related to the enumeration and other relevant code to deduce further.

What's a good maintainable way to name methods that are intended to be called by IBActions?

I am creating function (for example) to validate content, then if it is valid, close the view, if it is not, present further instructions to the user. (Or other such actions.) When I go to name it, I find myself wondering, should I call it -doneButtonPressed or -validateViewRepairAndClose? Would it be better to name the method after what UI action calls it, or name it after what it does? Sometimes it seems simple, things like -save are pretty clear cut, other times, and I can't thing of a specific example right off, but I know some have seemed like naming them after what they do is just so long and confusing it seems better to just call them xButtonPressed where x is the word on the button.
It's a huge problem!!! I have lost sleep over this.
Purely FWIW ... my vote is for "theSaveButton" "theButtonAtTheTopRight" "userClickedTheLaunchButton" "doubleClickedOnTheRedBox" and so on.
Generally we name all those routines that way. However .. often I just have them go straight to another routine "launchTheRocket" "saveAFile" and so on.
Has this proved useful? It has because often you want to launch the rocket yourself ... in that case call the launchTheRocket routine, versus the user pressing the button that then launches the rocket. If you want to launch the rocket yourself, and you call userClickedTheLaunchButton, it does not feel right and looks more confusing in the code. (Are you trying to specifically simulate a press on the screen, or?) Debugging and so on is much easier when they are separate, so you know who called what.
It has proved slightly useful for example in gathering statistics. The user has requested a rocket launch 198 times, and overall we've launched the rocket 273 times.
Furthermore -- this may be the clincher -- say from another part of your code you are launching the rocket, using the launch-the-rocket message. It makes it much clearer that you are actually doing that rather than something to do with the button. Conversely the userClickedTheLaunchButton concept could change over time, it might normally launch the rocket but sometimes it might just bring up a message, or who knows what.
Indeed, clicking the button may also trigger ancillary stuff (perhaps an animation or the like) and that's the perfect place to do that, inside 'clickedTheButton', as well as then calling the gutsy function 'launchTheRocket'.
So I actually advocate the third even more ridiculously complicated solution of having separate "userDidThis" functions, and then having separate "startANewGame" functions. Even if that means normally the former does almost nothing, just calling the latter!
BTW another naming option would be combining the two... "topButtonLaunchesRockets" "glowingCubeConnectsSocialWeb" etc.
Finally! Don't forget you might typically set them up as an action, which changes everything stylistically.
[theYellowButton addTarget:.. action:#selector(launchRockets) ..];
[theGreenButton addTarget:.. action:#selector(cleanUpSequence) ..];
[thatAnimatingButtonSallyBuiltForUs addTarget:.. action:#selector(resetAll) ..];
[redGlowingArea addTarget:.. action:#selector(tryGetRatingOnAppStore) ..];
perhaps that's the best way, documentarily wise! This is one of the best questions ever asked on SO, thanks!
I would also go with something along the lines of xButtonPressed: or handleXTap: and then call another method from within the handler.
- (IBAction)handleDoneTap:(id)sender {
[self closeView];
}
- (void)closeView {
if ([self validate]) {
// save and close
}
else {
// display error information
}
}