Objective-C Misc

Logging

Logging message in Objective-C

NSLog ( @"Logging message: %@", [myObject myMehtod] );

Objective-C For loop

Looping an Objective-C array with a for loop

NSArray *myList = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];
 
for (NSString *myData in myList) {
    NSLog(@"data: %@", myData);
}

Objective-C Thread

To support threading and exception handling feature, turn on the following compiler flag

-fobjc-exceptions

Create synchronize block in Objective-C

- (void)myMethod
{
    ...
    @synchronized(self) {
        ...
    }
    ...
}
  • The thread acquired the lock identified by @synchronized will enter the critical block
  • Others will be block until the lock is released

Objective-C Exception Handling

Throw an exception

NSException *exception = [NSException exceptionWithName: @"MyException"
                                                 reason: @"The reason"
                                               userInfo: nil];
@throw exception;

Exception throwing and catching is resource intense in Objective-C

try ... catch ... finally in Objective-C for exception catching

@try {
   ...
}
@catch (NSException *exception) {
   ...
}
@catch (id e) {
   // Catch any un-caught exception
   ...
}
@finally {
  // Will always execute regardless there is an exception or not
   ...
}