搜尋

首頁  >  問答  >  主體

objective-c - 求助~ Unicode 轉 NSString

如題,網路上找了都是比較舊的 關於 NSPropertyListSerialization的,可是這個類別庫github上都找不著下載啊...

欧阳克欧阳克2745 天前994

全部回覆(2)我來回復

  • 習慣沉默

    習慣沉默2017-06-21 10:13:44

    API都寫的很 清楚了 Use propertyListWithData:options:format:error: instead.
    [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NULL error:NithData:tempData options:NSPropertyListImmutable format:NULL error:NithData]; 系統函式庫不能解決問題?

    回覆
    0
  • 仅有的幸福

    仅有的幸福2017-06-21 10:13:44

    測試程式碼:

    NSString *dataStr = @"求助~ Unicode 转 NSString";
        
    NSString *utf8Str = [NSString replaceUnicode:dataStr];    
    NSLog(@" utf8Str = %@",utf8Str);
        
    NSString *unnicodeStr = [NSString utf8ToUnicode:utf8Str];    
    NSLog(@" unicode = %@",unnicodeStr);

    運行結果:

    把這兩個方法寫到NSString分類中

    //Unicode转UTF-8
    + (NSString*) replaceUnicode:(NSString*)aUnicodeString
    {
        NSString *tempStr1 = [aUnicodeString stringByReplacingOccurrencesOfString:@"\u" withString:@"\U"];
        
        NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\""];
        
        NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
        
        NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
        
        NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                               
                                                               mutabilityOption:NSPropertyListImmutable
                               
                                                                         format:NULL
                               
                                                               errorDescription:NULL];
        
        return [returnStr stringByReplacingOccurrencesOfString:@"\r\n" withString:@"\n"];
        
    }
    // utf8转unnicode
    +(NSString *) utf8ToUnicode:(NSString *)string
    {
        NSUInteger length = [string length];
        
        NSMutableString *str = [NSMutableString stringWithCapacity:0];
        
        for (int i = 0;i < length; i++) {
            
            unichar _char = [string characterAtIndex:i];
            //判断是否为英文和数字
            if (_char <= '9' && _char >= '0') {
                
                [str appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
            } else if(_char >= 'a' && _char <= 'z') {
                
                [str appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
            } else if(_char >= 'A' && _char <= 'Z') {
                
                [str appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
            } else {
                [str appendFormat:@"\u%x",[string characterAtIndex:i]];
            }
        }
        return str;
    }

    回覆
    0
  • 取消回覆