使用base64时出现奇怪的目标c错误

时间:2012-08-16 14:48:46

标签: objective-c

我刚刚尝试了以下代码段并且我遇到了错误: -

#import "JSONKit.h"
#import "Base64.h"
#import <Foundation/Foundation.h>

int main() { 
NSMutableDictionary *dict = [NSMutableDictionary dictionary]; [dict setObject:(id)@"value" forKey:(id)@"key"];

for(id key in dict) NSLog(@"%@\t%@\n", key, [dict objectForKey:key]);

[Base64 initialize]; 
NSData *jsonstr = [dict JSONStringWithOptions:JKSerializeOptionNone error:nil]; 
NSString *val = [Base64 encode: jsonstr]; 
NSLog(@"%@\n", val);

return 0; 
}

我得到的错误是: -

test.m: In function ‘main’:
test.m:13: warning: incompatible Objective-C types initializing ‘struct NSString *’, expected ‘struct NSData *’
Undefined symbols:
  "_OBJC_CLASS_$_Base64", referenced from:
      __objc_classrefs__DATA@0 in cc23xlpr.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

为了删除警告,我将一行更改为: -

NSData *jsonstr = (NSData *)[dict JSONStringWithOptions:JKSerializeOptionNone error:nil];

然而,错误仍然存​​在 - 对于Objective-C来说是新手我发现错误相当神秘,有人可以帮助我理解问题的根源/同样的解决方案吗?

1 个答案:

答案 0 :(得分:1)

我想,[dict JSONStringWithOptions:JKSerializeOptionNone error:nil]方法返回字符串,如果你想将该字符串序列化为NSData,你应该遵循:

[Base64 initialize]; 
NSString *jsonStr = [dict JSONStringWithOptions:JKSerializeOptionNone error:nil]; 
NSData *jsonstrData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *val = [Base64 encode: jsonstrData]; 
NSLog(@"%@\n", val);