Skip to content

Commit 02619d9

Browse files
committed
Avoided double string<>data conversion in inits
Removed double string<>data conversion in -(id)initWithString:(NSString *)string usingEncoding:(NSStringEncoding)encoding error:(JSONModelError**)err and -(instancetype)initWithData:(NSData *)data error:(NSError *__autoreleasing *)err methods
1 parent 4c4c1d3 commit 02619d9

File tree

2 files changed

+19
-18
lines changed

2 files changed

+19
-18
lines changed

JSONModel/JSONModel/JSONModel.m

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -114,13 +114,21 @@ -(id)init
114114

115115
-(instancetype)initWithData:(NSData *)data error:(NSError *__autoreleasing *)err
116116
{
117-
//turn nsdata to an nsstring
118-
NSString* string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
119-
if (!string) return nil;
120-
121-
//create an instance
117+
if (!data) return nil;
118+
119+
//read the json
122120
JSONModelError* initError = nil;
123-
id objModel = [self initWithString:string usingEncoding:NSUTF8StringEncoding error:&initError];
121+
id obj = [NSJSONSerialization JSONObjectWithData:data
122+
options:kNilOptions
123+
error:&initError];
124+
125+
if (initError) {
126+
if (err) *err = [JSONModelError errorBadJSON];
127+
return nil;
128+
}
129+
130+
//init with dictionary
131+
id objModel = [self initWithDictionary:obj error:&initError];
124132
if (initError && err) *err = initError;
125133
return objModel;
126134
}
@@ -141,21 +149,11 @@ -(id)initWithString:(NSString *)string usingEncoding:(NSStringEncoding)encoding
141149
return nil;
142150
}
143151

144-
//read the json
145152
JSONModelError* initError = nil;
146-
id obj = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:encoding]
147-
options:kNilOptions
148-
error:&initError];
149-
150-
if (initError) {
151-
if (err) *err = [JSONModelError errorBadJSON];
152-
return nil;
153-
}
154-
155-
//init with dictionary
156-
id objModel = [self initWithDictionary:obj error:&initError];
153+
id objModel = [self initWithData:[string dataUsingEncoding:encoding] error:&initError];
157154
if (initError && err) *err = initError;
158155
return objModel;
156+
159157
}
160158

161159
-(id)initWithDictionary:(NSDictionary*)dict error:(NSError**)err

JSONModelDemo_iOS/MasterViewController.m

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,9 @@ -(void)viewDidAppear:(BOOL)animated
122122
TopModel* tm = [[TopModel alloc] initWithString:json error:nil];
123123
NSLog(@"tm: %@", tm.toDictionary);
124124
NSLog(@"to string: %@", tm.toJSONString);
125+
tm = [[TopModel alloc] initWithData:[json dataUsingEncoding:NSUTF8StringEncoding] error:nil];
126+
NSLog(@"tm - WithData : %@", tm.toDictionary);
127+
NSLog(@"to string - WithData : %@", tm.toJSONString);
125128
}
126129

127130
-(IBAction)actionLoadCall:(id)sender

0 commit comments

Comments
 (0)