我正在尝试读取包含由NSString类型和NSMutableArrays组成的联系信息对象的JSON文件。目前,我正在使用NSData读取整个文件,然后解析它。我已经使用了这里提到的Stig的例子:SBJson4Parser Example
SBJson4ValueBlock block = ^(id obj, BOOL *stop) {
NSLog(@"Found: %@", @([obj isKindOfClass:[NSDictionary class]]));
//contactsData *contact = obj;
NSDictionary *contact = obj;
NSLog(@"Contact: %@",contact);
/* NSString *fName, *lName;
fName = [contact objectForKey:@"mFirstName"];
lName = [contact objectForKey:@"mLastName"];
NSLog(@"First Name: %@",fName);
NSLog(@"Last Name: %@",lName);
*/
};
SBJson4ErrorBlock eh = ^(NSError* err){
NSLog(@"Oops: %@",error);
};
NSLog(@"Parse work");
id parser = [SBJson4Parser multiRootParserWithBlock:block
errorHandler:eh];
//uint8_t buf[1024];
//unsigned int len = 0;
NSLog(@"Trying to push stream to data");
//[inputStream read:buf maxLength:len];
NSData *data = [NSData dataWithContentsOfFile:filePath options:NSUTF8StringEncoding error:NULL];
//id data = [json da:NSUTF8StringEncoding];
SBJson4ParserStatus status = [parser parse:data];
NSLog(@"Status: %u",status);
现在,由于社交网络,人们似乎有数百甚至数千个联系人。这会导致iOS设备上更大的内存占用吗?如果是这样,我如何解析流中的单个对象?如果我必须使用委托,我将非常感谢一个例子。
请注意,我是iOS开发和Objective-C的新手。
The structure of the json file in question:
{
"mAddresses": [
],
"mContactPhoto": "",
"mDisplayName": ",tarun,,,,israni,,",
"mPhoneNumberList": [
{
"mLabel": "_$!<Home>!$_",
"mNumber": "(988) 034-5678",
"mType": 1
}
]
}{
"mAddresses": [
],
"mContactPhoto": "",
"mDisplayName": ",Sumit,,,,Kumar,,",
"mPhoneNumberList": [
{
"mLabel": "_$!<Home>!$_",
"mNumber": "(789) 034-5123",
"mType": 1
}
]
}
答案 0 :(得分:0)
您的解决方案看起来应该对我有用。如果您的文件太大而您不想将其全部保存在内存中,即您希望避免使用此行:
NSData *data = [NSData dataWithContentsOfFile:filePath options:NSUTF8StringEncoding error:NULL];
然后你可以使用NSInputStream(未经测试,但希望你得到要点):
id parser = [SBJson4Parser multiRootParserWithBlock:block
errorHandler:eh];
id is = [NSInputStream inputStreamWithFileAtPath:filePath];
[is open];
// buffer to read from the input stream
uint8_t buf[1024];
// read from input stream until empty, or an error;
// better error handling is left as an exercise for the reader
while (0 > [is read:buffer maxLength: sizeof buffer]) {
SBJson4ParserStatus status = [parser parse:data];
NSLog(@"Status: %u",status);
// handle parser errors here
}
[is close];
但是,您仍然必须阅读并解析整个文件,以确保找到特定的联系人。 无法以这种方式只读取特定联系人。如果您经常这样做,您可能希望以不同的方式存储联系人以更好地支持该方案。一种方法是使用例如SQLLite。