Skip to content

Instantly share code, notes, and snippets.

@JohannMG
Created October 12, 2021 16:59
Show Gist options
  • Save JohannMG/03268cfe23630d76ab864535ac88ee74 to your computer and use it in GitHub Desktop.
Save JohannMG/03268cfe23630d76ab864535ac88ee74 to your computer and use it in GitHub Desktop.
I taught a quick class on how objective C selectors work
objective-c selectors:
SEL
The alternative to blocks.
This is how delegate/protocol patterns work. (another talk)
Most common API is for UIButtons / UIControls
[button addTarget:self action:@selector(aMethod:) forControlEvents:UIControlEventTouchDown];
-(void)aMethod:(UIButton*)sender
Calls the selector on the target.
A selector is it's own type SEL:
SEl selector = @selector(aMethod)
^ notice no * because it's not a pointer
objc uses a integer to store the method name
@selector(aMethod) ---at runtime---> 72388763
Must be done at runtime because objective c is a dynamic language: implementations of functions can be changed while the applicaiton is running using a method called Swizzling (another talk)
So how is a method sent in objective-c?
[object method:parameter] could also be written as [target selector:parameter]
[joe performSelector:@selector(sayHelloToPerson:) withObject:bill];
we can also check if a class implments a method with:
[joe respondsToSelector:methodToCall]
And what it means for properties:
All properties are accessed via selectors on getter methods on functions.
@property (nonatomic) NSString *nonatomicString;
creates getNonatomicString and setNonatomicString automatically
a property access for obj.nonatomicString is = [obj getNonatomicString]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment