Is there a way of specifying a selector without the #selector syntax / what is going on behind the scenes with #selector - objective-c

Is #selector a convenience syntax for some sort of longer C syntax, or is it a "hard wired" part of the Objective-C language/compiler? For example, I know that when I call #property, depending on the arguments, different equivalent Objective-C code is "generated" re: getters and setters. What is going on behind the scenes with #selector? Is it specifying an Objective-C message?

#selector() is a part of the language. It specifies literal SEL just like #"" specifies a literal NSString.
It's worth understanding that #selector represents a selector, not a message. A selector is just a name. It's just one small part of a message. It doesn't even carry type information.
Also note that #property doesn't generate anything. It just promises that the object will respond to one or two selectors (the getter and the setter). There are several ways to fulfill that contract. #synthesize is just one of them. You can also manually implement the needed methods, or use #dynamic to promise that it will somehow be handled at runtime.

To answer the question in your title, NSSelectorFromString will let you create a selector from an NSString (you can also do the opposite with NSStringFromSelector), although it's more efficient to use #selector.

Related

How does accessing ivars directly differ from using an accessor?

So in some of the codes I see, they access an objects ivar directly instead of using accessors . What are the advantages of using them instead of accessors?
So how would this
thing = object->ivar
differ from this?
thing = object.ivar
Thanks.
First let me say, I totally loathe the Objective-C dot notation. It sacrifices understandability for brevity and that is a bad thing. In fact, the other two answers here both show evidence of the kind of confusion dot notation introduces.
Having got the rant out of the way, I'll now try to answer the question.
Under the hood, Objective-C objects are implemented as pointers to C structs. This is why
obj->ivar
sometimes works. Given that it's a C struct
(*obj).ivar
should also work exactly as you would expect for C. Having said that, you can make ivars private or protected, in which case using the above outside a scope where they are visible will cause a compiler error.
The dot operator when applied to an Objective-C object (which is a pointer don't forget) has a totally different meaning. It's syntactic sugar for sending an accessor message to the object meaning that:
foo = obj.property;
obj.property = foo;
is identical in effect to
foo = [obj property];
[obj setProperty: foo];
That is all there is to dot notation. If you go through your code changing all instances of the first form to instances of the second form, you have done everything the compiler does wrt dot notation.
In particular
you do not need a declared #property to use dot notation. You can declare the set and get accessors in the traditional way as Objective C methods, although it is definitely best practice to use #property declarations for things that are logically properties.
you do not need a backing instance variable. There's no reason why your getters and setters can't calculate values.
Given the above, the major difference between obj->ivar and obj.ivar is that the former modifies the ivar directly and latter invokes an accessor, this means that the latter can do any memory management stuff needed (retains, releases, copies etc) and can also invoke key value observing.
This is one thing with a huge difference between c/c++ and objective-c.
In C/C++ the . accesses the variable directly and the -> accesses the variable if it's a pointer to the variable, so basically it is the same.
In Objective-C the . is a shortcut to access the property using the setter and getter function and it is always using those functions. You can't access ivars with it if there is no property with that name.
Some say it's "dirty" to allow direct access to the variables. If more people work on the code it's "cleaner" to use accessors because it might be easier to debug where variables are changed since you can always break in the setter.
You can even do "bad" things with it, like:
NSArray *array = [NSArray alloc] init];
int count = array.count;
array.release;
this will technically work, because the array.release is a shortcut for [array release] but it is bad style to use . for other things then properties.
The advantage of properties is that they call methods that work with your ivars, in stead of calling the ivars directly, so you can do things like this:
-(void)setFrame:(CGRect)frame
{
if([self frameIsValid:frame])
{
if(self.flipsFrames)
{
frame.size = CGSizeMake(frame.size.height,frame.size.width);
}
[super setFrame:frame];
[delegate viewSubclass:self ChangedFrameTo:frame];
}
}
Four advantages shown here are:
The possibility to override
The possibility to check a given value
The possibility to alter a given value (use with caution)
A way to react to calls
Another advantage:
-(NSInteger) amountOfMinutes
{
return amountOfSeconds * 60;
}
You can use 1 ivar for multiple properties, saving memory and preventing/reducing redundancy, while keeping useful different formats.
There's not really an advantage to using ivars, except when you don't want to use a property so your class is more encapsulated. That does not make it impossible to reach, but it makes it clear it isn't supposed to be reached.
All ivars are private. There is no way to access them directly from outside the object. Therefore, both of your code samples are equivalent, in ObjC terms.
When you call object.ivar, what you are really doing is calling object's ivar selector. This may be either a getter method that you wrote yourself, or more likely, a synthesized getter method that you created with #synthesize.
thing, however, is an ivar. Your code would be calling the ivar selector on object and assigning the result directly to your instance's thing ivar.
If you had instead written it as self.thing = object.ivar, then you would be using your instance's setter method to assign to thing.
Some of the advantages of using accessors (specifically, synthesized properties) in ObjC are KVO/KVC compliance; better concurrency support; access control (readonly, readwrite); as well as all of the advantages that accessors give you in any other OO language.

Dynamically bind method to selector at runtime

I want to programmatically associate code with selectors. I am not clear on how to do that in Objective C. In Ruby, I might override method_missing. In Common Lisp, I might define a macro. In Objective C, I can get part of the way there with #dynamic properties, but I'm unclear on how to actually implement them.
Here's a concrete example: I want to use an NSMutableDictionary to persistently store parts of my object. My class has two methods that handle the basic functionality, and a bunch of dynamic properties (matching #propertys exist in #interface):
#dynamic name;
#dynamic age;
#dynamic favoriteColor;
- (id)accessor:(NSString*)name {
return [[self dict] objectForKey:name];
}
- (void)mutator:(NSString*)name value:(id)value{
[[self dict] setObject:value forKey:name];
[[self dict] writeToFile:[self filename] atomically:YES];
}
Now I am looking for a way to translate a call like
[myInstance setName:#"iter"];
into
[self mutator:#"name" value#"iter"];
I wonder if there is an idiomatic way to do that in ObjC.
This isn't really an idiomatic thing to do in Objective-C, and there's certainly nothing like a Lisp macro available. NSObject and the runtime do, however, provide three possible points for you to intercept and handle messages referring to methods that don't otherwise exist. In the order they are used by the runtime: resolveInstanceMethod:, forwardInvocation: and doesNotRespondToSelector:. The documentation for each of them explains their use and gives some examples.
The first requires you to actually write out and add a method to the class, which doesn't seem like it will achieve the dynamic state of affairs you desire. The last by default raises an exception and doesn't provide for any return value. Almost certainly, forwardInvocation is what you want to look into. It allows your object to ask another object to handle a method call, including the passed arguments; it should be possible for you to make your object handle the call itself in a way that at least gets you close to what you're going for.
Also, the "Message Forwarding" chapter of the Runtime Programming Guide gives some examples of tasks similar to your requirement.
If an object does not have the method that you have called on it you can override forwardInvocation to delegate the method call to another object.
You can use the Objective-C runtime functions along with resolveInstanceMethod:. There's a short example in the resolveInstanceMethod: docs.

How does dot syntax work without explicit #property in Objective-C?

I wrote a setter and getter method following Apple's conventions and noticed that despite having no variable I can still access the setter and getter using the dot syntax. Is this normal behavior? What enables this feature?
Example:
// Header definition. Keep in mind there is no class variable or #property for height.
- (void)setHeight:(float)height;
- (float)height;
// else using the dot syntax.
object.height = 10.0f;
A property-access expression is equivalent to a message expression:
[object setTexture:tex];
A property declaration is equivalent to one (readonly) or two (readwrite/default) instance-method declarations. Keywords like retain tell the compiler how to implement the method if you tell it to do so (#synthesize).
However, you can skip the property declaration and declare the methods directly, as shown in your question. You can't synthesize their implementations, since you need a property declaration for that (otherwise, it wouldn't know what memory-management policy to use: assign, retain, or copy), but you can always implement the methods yourself.
Then, even though you declared and implemented the methods yourself, since property-access syntax and message syntax are equivalent to each other, you can use the methods whichever way you want: With a message expression, or with a property-access expression.
Some would consider it bad form, though, to use property access expressions on anything but a formal #property (e.g., myString.length or myArray.count or myView.frame). It definitely is bad form to use a property-access expression to send a message that doesn't access any kind of property; foo.retain.autorelease, for example, is bad and wrong: It reeks of trying to pretend you're programming some other language than Objective-C.
Incidentally, a property and a variable are unrelated. A #property will ordinarily be backed by an instance variable, but this is not required: You could store the property's value inside another object, or convert it to and from some other format, or both. Likewise, accessing a property (which is an accessor message) and accessing an instance variable (which is just accessing a variable, nothing more) are very different.

objective c - delegate and events

I am looking for good example code for using delegate and events in objective c?
i am familiar with delegate and events in C#.
so if someone can help me with few lines of code it will be very helpful.
Selectors (equivalent of C# delegates)
Beware, C# has a term called "delegate" and Objective-C has a term called "delegate", but the two have hardly anything in common.
The C# "delegate" is essentially a type-safe function pointer. The equivalent of a function pointer in Objective-C is called a "selector".
To declare a parameter, member variable or local variable to be a selector, declare the type as SEL. For instance in the header file for the NSTimer class you can find this method:
- (id)initWithFireDate:(NSDate *)date
interval:(NSTimeInterval)seconds
target:(id)target
selector:(SEL)aSelector
userInfo:(id)userInfo
repeats:(BOOL)repeats;
This means you're meant to pass a selector as the fourth argument when using this method. You can call it like this:
[[NSTimer alloc] initWithFireDate: someDate
interval: someInterval
target: self
selector: #selector(myTimerCallback:)
userInfo: nil
repeats: NO];
As you can see, by writing #selector(some-name-here), I can construct a new selector (similar to how I can construct a new string by writing #"some text here"). Objective-C methods have "holes" in them where arguments are inserted, and these holes are preceded by colons. When writing a selector as above, you keep the colons but you remove all else. For instance you can write something like #selector(firstPart:secondPart:thirdPart:).
The documentation of the method that accepts a selector should usually state what sort of signature it is allowed to have. The compiler will NOT enforce this for you (this is very different from C# delegates).
Notice also that the method above asks for a "target" parameter. This is typically the object the selector will be called on. Notice that the target is the completely untyped id. The compiler does not try to enforce that the object you pass in as target actually will respond to the method indicated by the selector. If it doesn't respond, then that is a runtime error. This is part of the dynamic nature of Objective-C.
(The Objective-C "delegate" concept is really just the delegate pattern (look it up), which is very prevalent in Objective-C, often used where other langauges would use inheritance.)
Events and Actions
Regarding events, there is an NSEvent class, but I have not yet had any experience with it. It seems to be for fairly low-level handling of GUI events. The C# use for events is probably more akin to "actions" in Objective-C.
Typically, a GUI component such a button has an "action" and a "target" associated with it. You can set these either in code or in Interface Builder. The target is as explained above -- an object on which a method will be called. And the "action" is in fact just a selector.
Please read the section "The Target-Action Mechanism" of this Cocoa Fundamentals article in the Apple docs. In fact that whole page is relevant to both parts of your question, so I recommend it highly.
The above answer is certainly correct. However, if you are looking for a way to implement the publisher/subscriber pattern then you should check out the NSNotificationCenter. This post has a good example.

How can I tell the compiler that my class resolves methods dynamically?

I have a class which uses resolveInstanceMethod to dynamically implement methods.
When I call the dynamically implemented methods from other parts of the code, the compiler emits a warning that the object may not respond to the selector. I would like the compiler to not emit such warnings for this class, but I don't want to suppress warnings when I invoke an invalid selector on other classes. Is this possible?
Assuming you know the method signatures that will be dynamically resolved at compile time, you can declare 'em in an informal category:
#interface MyDynamicallyResolvingClass(MethodsThatWillResolveAtRuntime)
... declare the methods here ...
#end
No need to provide an implementation.
If you don't know the signatures -- if the method names are dynamic, too -- then you'll need to use either -performSelector: (or the single or double object argument variants) or you will likely want to use NSInvocation, unless performance is a major concern (if it is, there are alternative solutions that are significantly more fiddly).
Use performSelector:
It's equivalent to sending a message directly to the receiver, however, it allows you to send messages that aren’t determined until runtime.
If your methods take one or two arguments, you can use the sisters of this method: – performSelector:withObject: and – performSelector:withObject:withObject:
If your methods have more than two arguments, or arguments that are not of object type, this answer is not adapted.