我有一个具有一对一关系的核心数据对象。所以例如
person.mothername person.fathername person.childrennames <- this is a NSSet
现在我想通过一个HTTP请求立即从iPhone发布到我们的服务器。可以这样做吗?
我现在用于没有NSSet的简单示例的代码: 设置参数:
params = [NSDictionary dictionaryWithObjectsAndKeys:
self.person.mothername, @"mothername",
self.person.fathername, @"fathername",
nil];
self.httpRequest = [[HTTPRequest alloc] init];
self.httpRequest.delegate = self;
[self.httpRequest httpPOST:SERVER_POST_PERSON withParams:params];
然后下一步(=直截了当):
- (BOOL)httpPOST:(NSString *)url withParams:(NSDictionary *)params {
const char *strUrlConst = (const char*)[[self buildParams:params] UTF8String];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[NSData dataWithBytes:strUrlConst length:strlen(strUrlConst)]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
self.responseData = [[NSMutableData data] retain];
return YES;
}
return NO;
}
那么最后的方法(直截了当?):
- (NSString *)buildParams:(NSDictionary *)params {
NSString *builtParams = [[[NSString alloc] init] autorelease];
int i = 0;
for (NSString *key in [params allKeys]) {
NSString *value = [self escapeString:[params objectForKey:key]];
if (!value) {
continue;
}
if (!i++) {
builtParams = [builtParams stringByAppendingString:[NSString stringWithFormat:@"%@=%@", key, value]];
} else {
builtParams = [builtParams stringByAppendingString:[NSString stringWithFormat:@"&%@=%@", key, value]];
}
}
NSLog(@"PARAMS: %@", builtParams);
return builtParams;
}
答案 0 :(得分:0)
为什么不使用JSON?
像SBJson这样的库可以在一行代码中创建一个来自NSDictionary的JSON字符串(IIRC:[params JSONRepresentation])。使用NSString的百分比esacpes方法对它进行URL编码是很简单的。
在服务器端,应该有大量的JSON库可供选择来解析数据。
答案 1 :(得分:0)
您可以使用NSSet
的{{1}}和-allObjects
将其转换为+setWithArray:
并返回。