Potatotips#7: Box C String Tip

Potatotips#7: Box C String Tip

0e726052fdb28ba1c004aa90eccbe261?s=128

Shin Yamamoto

May 15, 2014
Tweet

Transcript

  1. Box C String Tip potatotips #7 @SCENEE / iOS

  2. ࣗݾ঺հ • @SCENEE : “Shin Yamamoto” • iOSΞϓϦέʔγϣϯ։ൃ • UIEvolution

    K.K. (ຊࣾ͸Seattle)
  3. Box C String • @(<expression>)ͷBoxϦςϥϧͰɺchar* ΍ɺconst char *͔ΒNSString΋ੜ੒Ͱ͖· ͢ɻ •

    ※Τϯίʔυ͕UTF8Ͱɺ\0͕ऴ୺ͷจࣈྻΛ ૝ఆ͍ͯ͠·͢
  4. Use cases • libXMLͰɺύʔεͨ͠஋ΛNSString΁ม׵͢ Δͱ͖ • C༝དྷͷϥΠϒϥϦͷจࣈྻΛϩάग़ྗ͢Δͱ ͖

  5. Use cases • libXMLͰɺύʔεͨ͠஋ΛNSString΁ม׵͢ Δͱ͖ • C༝དྷͷϥΠϒϥϦͷจࣈྻΛϩάग़ྗ͢Δͱ ͖ • One

    More!!
  6. Macroͷreplacement token ΛNSStringͰऔಘ͢Δ

  7. ↓ͷΑ͏ʹMacroͷ஋Λ char*ͱͯ͠ औΓग़ͯ͠ɺNSStringͱͯ͠ѻ͑Δ #define __str(x) #x #define str(x) __str(x) #define

    FOO foo ! ! { NSLog(@"%@", @(str(FOO))); ——> “foo” }
  8. ͜ΕΛԠ༻͢Δͱ͜ΜͳϞσ ϧίʔυ͕ॻ͚·͢

  9. ·ͣɺҎԼͷΑ͏ʹmacroͰɺ͋Δ ActionΛఆٛ͠·͢ɻ #pragma mark ########################### ! #define __str(x) #x #define

    str(x) __str(x) ! #define Action1 saltAction #define Action2 garlicAction #define Action3 wasabiAction ! #pragma mark ###########################
  10. ࣍ʹɺ͜ΕΛར༻ͯ͠ɺUITableView༻ ͷϝχϡʔϞσϧΛ࡞Δͱ @interface PTMenu() @property NSArray *menuList; @end ! @implementation

    PTMenu ! - (instancetype)init { self = [super init]; if (self) { self.menuList = @[@{TITLE : @"Salt", ACTION : @(str(Action1)":")}, // ACTION : [NSString stringWithUTF8String:str(Action1)":"]}, @{TITLE : @"Garlic", ACTION : @(str(Action2)":")}, @{TITLE : @"Wasabi", ACTION : @(str(Action3)":")}, ]; } return self; }
  11. ͜Μͳ෩ʹɺSELΛ࢖ͬͯ ηϧબ୒࣌ͷϩδοΫΛॻ͚Δʂ #pragma mark - UITableView delegate - (void)tableView:(UITableView *)tableView

    didSelectRowAtIndexPath: (NSIndexPath *)indexPath { NSString *action = self.menuList[indexPath.row][ACTION]; SEL selector = NSSelectorFromString(action); if ([self respondsToSelector:selector]) { [self performSelector:selector withObject:self];// NOTE: Waring͸ɺ Actionͷϝιου͕ఆٛ͞Ε͍ͯΕ͹໰୊ͳ͍ɻ } } ! #pragma mark - Actions ! - (void)Action1:(id)sender { UIAlertView *av = [[UIAlertView alloc] init]; av.title = @(str(Action1)); [av addButtonWithTitle:@"OK"]; av.cancelButtonIndex = 0; [av show]; }
  12. References • http://stackoverflow.com/questions/195975/ how-to-make-a-char-string-from-a-c-macros- value • http://gcc.gnu.org/onlinedocs/cpp/ Stringification.html#Stringification