objective-c - 奇怪的 NSData 输出

标签 objective-c ios post utf-8 nsdata

我从以下代码中得到了一些意想不到的结果:

- (NSData *)postDataWithDict:(NSDictionary *)postDict
{
    // Assume key is urlValid
    NSUInteger postCount = [postDict count];
    NSMutableArray *buildArray = [[NSMutableArray alloc] initWithCapacity:postCount];
    for (NSString *key in postDict) {
        //post data is key=value&key=value&key=value...

        // start with key
        NSMutableString *arrayLine = [NSMutableString stringWithString:key];

        [arrayLine appendString:@"="];

        // analyze and then append value
        id postValue = [postDict objectForKey:key];
        if ([postValue isKindOfClass:[NSNumber class]]) {
            NSString *valueString = [NSString stringWithFormat:@"%@",postValue];
            [arrayLine appendString:valueString];
        }
        else if ([postValue isKindOfClass:[NSString class]]) {
            NSString *urlEncodedString = [self urlEncodeValue:postValue];
            [arrayLine appendString:urlEncodedString];
        }
        else {

            NSLog(@"postKey: %@, postValue class:%@", key, [postValue class]);
            NSError *jsonError = nil;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postValue
                                                               options:0
                                                                 error:&jsonError];
            if (jsonError != nil) {
                NSLog(@"JSON serialization failed: %@ - %@", [jsonError localizedDescription], [jsonError userInfo]);
                NSLog(@"value: %@", postValue);
            }
            else {
                // need to urlencode
                NSString *stringifyJSON = [NSString stringWithUTF8String:[jsonData bytes]];
                NSString *urlJSONstring = [self urlEncodeValue:stringifyJSON];
                [arrayLine appendString:urlJSONstring];
            }
        }
        [buildArray addObject:arrayLine];
    }
    NSString *postString = [buildArray componentsJoinedByString:@"&"];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];

    //testing
    NSLog(@"Post Dict: %@", postDict);
    NSLog(@"Post Array: %@", buildArray);
    NSLog(@"Post String: %@", postString);
    NSLog(@"Post Data: %@", [NSString stringWithUTF8String:[postData bytes]]);

    return postData;
}

我的//测试日志结果:

 Post Dict: {
    authenticationString = b3210c0bc6d2c47f4c2f7eeea12e063d;
    dataMode = updateSingle;
    dateCreated = "374300293.81108";
    dateModified = "374609294.313093";
    dateSynced = "374610683.588062";
    entityName = CommodityTypes;
    myName = 21;
    sortKey = 21;
    username = iPhoneAdamek;
    usernameString = iPhoneAdamek;
    uuidKey = "53403EAE-DD4F-4226-A979-316EF7F43991";
}

Post Dict 看起来不错。正是我想要的。

2012-11-14 13:31:23.640 FoodyU[11393:907] Post Array: (
    "myName=21",
    "dataMode=updateSingle",
    "dateSynced=374610683.588062",
    "uuidKey=53403EAE-DD4F-4226-A979-316EF7F43991",
    "sortKey=21",
    "dateModified=374609294.313093",
    "entityName=CommodityTypes",
    "dateCreated=374300293.81108",
    "authenticationString=b3210c0bc6d2c47f4c2f7eeea12e063d",
    "usernameString=iPhoneAdamek",
    "username=iPhoneAdamek"
)

Post Array 看起来不错。字符串都设置为连接成 HTTP POST 字符串。

2012-11-14 13:31:23.641 FoodyU[11393:907] Post String: myName=21&dataMode=updateSingle&dateSynced=374610683.588062&uuidKey=53403EAE-DD4F-4226-A979-316EF7F43991&sortKey=21&dateModified=374609294.313093&entityName=CommodityTypes&dateCreated=374300293.81108&authenticationString=b3210c0bc6d2c47f4c2f7eeea12e063d&usernameString=iPhoneAdamek&username=iPhoneAdamek

Post String 看起来不错。我已准备好将其转换为数据以在 [NSMutableURLRequest setHTTPBody:postData] 中使用。

2012-11-14 13:31:23.643 FoodyU[11393:907] Post Data: myName=21&dataMode=updateSingle&dateSynced=374610683.588062&uuidKey=53403EAE-DD4F-4226-A979-316EF7F43991&sortKey=21&dateModified=374609294.313093&entityName=CommodityTypes&dateCreated=374300293.81108&authenticationString=b3210c0bc6d2c47f4c2f7eeea12e063d&usernameString=iPhoneAdamek&username=iPhoneAdamekoneAdamek;
    usernameString = iPhoneAdamek;
    uuidKey = "53403EAE-DD4F-4226-A

什么鬼??? &username=iPhoneAdamek 是如何变成 &username=iPhoneAdamekoneAdamek; usernameString = iPhoneAdamek; uuidKey = "53403EAE-DD4F-4226-A?

我是 Cocoa 的新手。有什么问题吗:

NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];

NSLog(@"Post Data: %@", [NSString stringWithUTF8String:[postData bytes]]);

最佳答案

你不应该使用 NSDataNSLog 作为,

NSLog(@"Post Data: %@", [NSString stringWithUTF8String:[postData bytes]]);

而是将其用作,

NSLog(@"Post Data: %@", [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]);

[NSString stringWithUTF8String:[postData bytes]] 总是返回意想不到的结果。

根据 documentation for bytes ,

bytes: 返回指向接收者内容的指针。

根据Apple documentation for stringWithUTF8String ,

stringWithUTF8String: 返回一个字符串,该字符串是通过从给定的 UTF8 编码字节 C 数组中复制数据而创建的。 参数:bytes - UTF8 编码的以 NULL 结尾的 C 字节数组。

因此,当您使用 [postData bytes] 时,它不是 NULL 终止的,因此当您使用 stringWithUTF8String 时,返回数据写入内存,直到遇到 NULL 终止。

关于objective-c - 奇怪的 NSData 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13385448/

相关文章:

javascript - 即时搜索延迟1个字符

javascript - 如何在flask中处理请求json数据

ios - 如何在 UIAlertController 中使用 UITextView

iphone - AVURLAsset 视频缓冲

objective-c - 如何从主屏幕通知用户 tvOS 应用程序中可用的新内容?

ios - 在 UI ImageView 中检索和显示保存的图像(文档文件夹)

iphone - 在实例变量中保存 block

ios - 快速更改仅选定片段的色调颜色

qt - 使用 Qt 发布数据时出错

objective-c - 从其他类访问 int 变量