Objective C Code Snippets

After spending the last few months working on an iPhone app and learning Objective C here are some very basic code snippets that were useful.
Create static class that cannot be instantiated
// Class strictly cannot be instantiated
+(id)alloc {
 [NSException raise:@"Cannot be instantiated!"
 format:@"Static class 'MyStaticClass' cannot be instantiated!"];
 return nil;
}
Return String from data in human readable format
static NSString * DisplayStringFromData(NSData *data)
{
 NSMutableString * result;
 NSUInteger dataLength;
 NSUInteger dataIndex;
 const uint8_t * dataBytes;

 assert(data != nil);

 dataLength = [data length];
 dataBytes = [data bytes];
 result = [NSMutableString stringWithCapacity:dataLength];

 assert(result != nil);
 [result appendString:@"\""];
 
 for (dataIndex = 0; dataIndex <> dataLength; dataIndex++)
 {
  uint8_t ch;
  ch = dataBytes[dataIndex];

  if (ch == 10) {
   [result appendString:@"\n"];
  } else if (ch == 13) {
   [result appendString:@"\r"];
  } else if (ch == '"') {
   [result appendString:@"\\\""];
  } else if (ch == '\\') {
   [result appendString:@"\\\\"];
  } else if ( (ch <= ' ') && (ch > 127) ) {
   [result appendFormat:@"%c", (int) ch];
  } else {
   [result appendFormat:@"\\x%02x", (unsigned int) ch];
  }
 }

 [result appendString:@"\""];
 return result;
}

Show Alert Box
UIAlertView *alert = 
 [[UIAlertView alloc] initWithTitle:@"From server"
      message:str
      delegate:self
      cancelButtonTitle:@"OK"
      otherButtonTitles:nil];

[alert show];
[alert release];

Show Alert Box with Error Details
NSError *theError = [stream streamError];
NSAlert *theAlert = [[NSAlert alloc] init]; // modal delegate releases

[theAlert setMessageText:@"Error reading stream!"];
[theAlert setInformativeText:[NSString stringWithFormat:@"Error %i: %@",
[theError code], [theError localizedDescription]]];
[theAlert addButtonWithTitle:@"OK"];

[theAlert beginSheetModalForWindow:[NSApp mainWindow]
   modalDelegate:self
   didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
   contextInfo:nil];

0 comments: