Skip to content

Instantly share code, notes, and snippets.

@tedhagos
Created November 20, 2012 06:43
Show Gist options
  • Save tedhagos/4116431 to your computer and use it in GitHub Desktop.
Save tedhagos/4116431 to your computer and use it in GitHub Desktop.
C Style strings to NSString
/*
An exercise on how to create NSString objects from C style chars
*/
#import <Foundation/Foundation.h>
#import <stdio.h>
@interface Person : NSObject {
NSString * name;
NSString * email;
}
@property (nonatomic, copy) NSString * name, * email;
@end
@implementation Person
@synthesize name, email;
- (void) foo {
NSLog(@ "Name : %@", name);
NSLog(@ "Email : %@", email);
}
@end
//////////////////////////////////
int main() {
char mname[20];
char memail[50];
char wait[1];
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
printf("Name : ");
fgets(mname,20, stdin);
printf("Email : ");
fgets(memail, 50, stdin);
printf("Name : %s", mname);
printf("Email : %s", memail);
NSString * nsname = [[ NSString alloc ] initWithBytes: mname length: sizeof(mname) encoding: NSASCIIStringEncoding];
NSString * nsemail = [[NSString alloc] initWithBytes: memail length: sizeof(memail) encoding:NSASCIIStringEncoding];
Person * ted = [[[Person alloc] init] autorelease];
[ted setName: nsname];
[ted setEmail: nsemail];
[ted foo];
[pool drain];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment