Must-Know Objective-C Interview Questions and Answers
Question: What is the purpose of @selector in Objective-C?
Answer:
In Objective-C, @selector
is a compiler directive used to represent a selector, which is a type that refers to the name of a method. A selector is essentially a way to refer to a method by its name so that it can be called dynamically during runtime. It is frequently used in contexts like message sending, target-action patterns, and performing selectors.
The primary purpose of @selector
is to allow method invocation in a flexible, dynamic way, which is a core feature of Objective-C’s runtime.
Key Concepts:
-
Selector: A selector is an object that represents the name of a method. It is typically used when you want to refer to a method without directly calling it. Selectors are used extensively in Objective-C to invoke methods dynamically, for example, in event handling or target-action systems.
A selector is essentially a method identifier. When you use
@selector
, you are telling the compiler to convert the method name into a selector. -
Target-Action Pattern: In the target-action pattern, a selector is passed to a method that will invoke the method on the specified object (the target). For instance, this is commonly used with UI controls like buttons.
Syntax:
The @selector
directive is used to create a selector by passing the name of the method (as a string) within the parentheses.
@selector(methodName)
For example:
SEL mySelector = @selector(buttonClicked:);
Here, @selector(buttonClicked:)
refers to a method called buttonClicked:
with a colon indicating that it takes one argument (the method signature - (void)buttonClicked:(id)sender
).
Common Use Cases:
-
Target-Action:
The
@selector
directive is commonly used in the target-action design pattern to specify which method to invoke when a certain event occurs (e.g., a button click).[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
In this example:
@selector(buttonClicked:)
specifies the methodbuttonClicked:
that will be called when the button is clicked.self
is the target (the object to which the method belongs).- The method is invoked when the
UIControlEventTouchUpInside
event is triggered.
-
Perform Selector:
You can use
@selector
with theperformSelector:
method to dynamically invoke a method at runtime.[self performSelector:@selector(updateUI)];
In this case, the
updateUI
method is called onself
at runtime. This allows for dynamic method invocation based on certain conditions. -
Checking Method Existence:
You can also use
@selector
in combination withrespondsToSelector:
to check whether an object can respond to a particular method. This is useful when you want to conditionally call a method.if ([object respondsToSelector:@selector(someMethod:)]) { [object performSelector:@selector(someMethod:) withObject:parameter]; }
In this example,
respondsToSelector:
checks if theobject
can respond to thesomeMethod:
method, andperformSelector:
is used to invoke it. -
Timers:
@selector
is used when specifying methods for NSTimer objects, such as calling a method after a delay or at regular intervals.[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
Here, the
timerFired:
method will be called every 1 second.
Example Usage:
1. Target-Action Example:
// Declare a method
- (void)buttonClicked:(UIButton *)sender {
NSLog(@"Button clicked!");
}
// Attach it to a UIButton
[myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
2. Using performSelector:
- (void)someMethod {
NSLog(@"This is someMethod!");
}
// Dynamically invoking the method
[self performSelector:@selector(someMethod)];
3. Using respondsToSelector:
if ([self respondsToSelector:@selector(optionalMethod)]) {
[self performSelector:@selector(optionalMethod)];
}
Key Points:
-
Dynamic Message Sending: The
@selector
is central to Objective-C’s dynamic message sending mechanism. It allows methods to be invoked by their names at runtime. -
Flexibility: It allows flexibility in coding because you can refer to methods dynamically, rather than having to call them explicitly by their names.
-
Method Signatures: When using
@selector
, the method signature (e.g.,buttonClicked:
) must match the method you intend to invoke. The colon:
indicates the presence of an argument in the method.
Summary:
@selector
is used to create a selector, which is a reference to a method’s name.- It is primarily used in target-action mechanisms, performing methods dynamically, and checking if an object can respond to a method via respondsToSelector.
- It allows for dynamic behavior and method invocation during runtime, which is a hallmark of Objective-C’s dynamic nature.
Question: What is the difference between copy
and mutableCopy
in Objective-C?
Answer:
In Objective-C, both copy
and mutableCopy
are methods used to create copies of objects, but they have important differences in terms of mutability. These methods are commonly used with mutable and immutable collections (like NSArray
, NSDictionary
, NSString
, etc.), as well as other objects that conform to the NSCopying
and NSMutableCopying
protocols.
1. copy
:
- Purpose: Creates an immutable copy of an object. This means the object returned by
copy
cannot be modified (if the original object was mutable). - Result: The resulting object is of the same class as the original object (if it’s already immutable) or a subclass that conforms to
NSCopying
. - Common Use Case: You use
copy
when you want to ensure that the copied object is immutable and cannot be modified by clients.
Example:
If you call copy
on a mutable collection, the result is an immutable copy.
NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"One", @"Two", @"Three", nil];
NSArray *immutableCopy = [mutableArray copy];
// mutableArray is still mutable, but immutableCopy cannot be modified.
[immutableCopy addObject:@"Four"]; // Compile-time error, immutableCopy is immutable
In the above example:
mutableArray
is a mutable collection, butimmutableCopy
is immutable, even though it was created from a mutable object.
2. mutableCopy
:
- Purpose: Creates a mutable copy of an object. This means the object returned by
mutableCopy
can be modified, even if the original object was immutable. - Result: The resulting object is a mutable version of the original object, or a subclass that conforms to
NSMutableCopying
. - Common Use Case: You use
mutableCopy
when you want to create a new mutable object based on an original one, regardless of whether the original object is mutable or immutable.
Example:
If you call mutableCopy
on an immutable object, the result is a mutable copy.
NSArray *immutableArray = @[@"One", @"Two", @"Three"];
NSMutableArray *mutableCopy = [immutableArray mutableCopy];
// mutableCopy can be modified, even though immutableArray is immutable.
[mutableCopy addObject:@"Four"]; // Works fine
In the above example:
immutableArray
is an immutable collection, butmutableCopy
is a mutable version of the original array.
Key Differences:
Aspect | copy | mutableCopy |
---|---|---|
Resulting Object | Immutable copy (if the object is mutable) | Mutable copy (even if the original is immutable) |
Original Object | If the original is mutable, the copy is immutable. If the original is immutable, the copy is also immutable. | Always creates a mutable object, regardless of the original’s mutability. |
Use Case | Ensures the object can’t be modified (protects the original from changes). | Allows modification of the copied object. |
Example | Copying a mutable object creates an immutable copy (NSArray from NSMutableArray ). | Copying an immutable object creates a mutable copy (NSMutableArray from NSArray ). |
When to Use copy
vs mutableCopy
:
-
Use
copy
: When you want to create a copy of an object and you don’t want it to be modified. This is useful when you need to protect the data from being changed, such as when you want to ensure that collections or strings cannot be altered.- For example, if you have a mutable object but want to guarantee it can’t be modified after it has been passed around in your code, you would use
copy
.
- For example, if you have a mutable object but want to guarantee it can’t be modified after it has been passed around in your code, you would use
-
Use
mutableCopy
: When you want a mutable copy of the object, so you can safely modify the copy without changing the original object. This is especially useful if the original object is immutable but you need a copy that you can modify later.- For example, if you’re working with an immutable object (e.g., an immutable array) and need to add/remove elements, you would use
mutableCopy
.
- For example, if you’re working with an immutable object (e.g., an immutable array) and need to add/remove elements, you would use
Example of copy
vs mutableCopy
:
// Original mutable object
NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"];
// Using copy (creates an immutable copy)
NSString *immutableCopy = [mutableString copy];
[immutableCopy appendString:@" World"]; // Compile-time error, immutableCopy is immutable
// Using mutableCopy (creates a mutable copy)
NSMutableString *mutableCopy = [mutableString mutableCopy];
[mutableCopy appendString:@" World"]; // Works fine, mutableCopy is mutable
In this case:
immutableCopy
is an immutable copy of the original mutable string, so you can’t modify it.mutableCopy
is a mutable copy of the original string, so you can modify it freely.
Summary:
copy
creates an immutable copy of an object, even if the original object is mutable.mutableCopy
creates a mutable copy of an object, allowing modifications to the copied object regardless of the original object’s mutability.- Use
copy
when you want to protect the object from modifications, and usemutableCopy
when you need to modify the copied object after it is created.
Read More
If you can’t get enough from this article, Aihirely has plenty more related information, such as Objective-C interview questions, Objective-C interview experiences, and details about various Objective-C job positions. Click here to check it out.
Tags
- Objective C
- ARC
- Automatic Reference Counting
- Objective C classes
- Objective C categories
- Objective C protocols
- Objective C memory management
- Strong
- Weak
- Assign properties
- @synthesize
- Objective C exceptions
- Objective C blocks
- Objective C methods
- Method swizzling
- Delegation pattern
- Key value coding
- Key value observing
- KVC
- KVO
- NSNotificationCenter
- Multi threading in Objective C
- NSThread
- GCD
- Copy vs mutableCopy
- @property
- @interface
- @implementation
- @end
- @selector
- Frame vs bounds
- Method implementation
- Blocks in Objective C
- Delegation in Objective C
- Objective c data structures
- NSArray
- NSDictionary
- NSSet
- Objc runtime
- Memory management in Objective C
- IOS programming
- Objective C design patterns