Objective-C Syntax
Objective-C's syntax is unique, blending C with Smalltalk-style message passing. Understanding its syntax is crucial for writing effective Objective-C code.
Message Passing Syntax
// Basic message passing
[receiver message];
// With arguments
[receiver messageWithArgument:arg1 andSecondArgument:arg2];
// Nested messages
NSString *result = [[object getFormatter] formatValue:value];
Note: The square bracket syntax is unique to Objective-C and different from the dot notation used in many other languages.
Method Declarations
// Instance method (- prefix)
- (returnType)methodName;
- (returnType)methodNameWithParameter:(parameterType)parameterName;
// Class method (+ prefix)
+ (returnType)classNameMethod;
// Example with multiple parameters
- (void)setName:(NSString *)name age:(NSInteger)age;
Data Types
Objective-C uses C's primitive types along with its own object types:
int
,float
,double
- Primitive numeric typesBOOL
- Boolean (YES/NO)id
- Generic object pointerNSInteger
,NSUInteger
- Platform-specific integersCGFloat
- Floating-point type for graphicsNSString
,NSNumber
,NSArray
- Foundation objects
String Syntax
// NSString literals (with @ prefix)
NSString *greeting = @"Hello, World!";
// String formatting
NSString *formatted = [NSString stringWithFormat:@"Count: %d, Price: %.2f", count, price];
// Mutable strings
NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"];
[mutableString appendString:@" World!"];
Control Structures
// If-else
if (condition) {
// code
} else if (anotherCondition) {
// code
} else {
// code
}
// Fast enumeration (for-in)
for (id object in collection) {
// code
}
// Traditional for loop
for (int i = 0; i < 10; i++) {
// code
}
// While loop
while (condition) {
// code
}
// Do-while
do {
// code
} while (condition);
Blocks Syntax
Objective-C blocks are similar to lambdas or closures in other languages:
// Simple block
void (^simpleBlock)(void) = ^{
NSLog(@"This is a block");
};
simpleBlock();
// Block with parameters and return value
double (^multiplyTwoValues)(double, double) = ^(double first, double second) {
return first * second;
};
double result = multiplyTwoValues(2.5, 4.0);
// Using blocks with methods
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"Object at index %lu: %@", (unsigned long)idx, obj);
}];
Warning: Be careful with retain cycles when using blocks that capture self
. Use weak references to avoid memory leaks.
Selector Syntax
Selectors are used to represent method names:
// Creating a selector
SEL mySelector = @selector(methodName:withParameter:);
// Performing selectors
if ([object respondsToSelector:mySelector]) {
[object performSelector:mySelector withObject:param1 withObject:param2];
}
// Using in target-action pattern
[button addTarget:self
action:@selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
Next: OOP Concepts in Objective-C