无法将NSArray写入文件

时间:2011-10-14 11:35:03

标签: objective-c cocoa nsarray gdata-api

我正在使用谷歌联系人数据目标c API来获取联系人。我从谷歌服务器获得联系人阵列现在我想写联系人到文件。我正在使用writeToFile:atomically:方法将数组写入文件但是这个方法对我不起作用,因为我觉得gdata API的输出数组不包含属性列表对象。请建议任何替代解决方案。

-(void)fetchData{
    GDataServiceGoogleContact *service=[[GDataServiceGoogleContact alloc] init];
    [service setShouldCacheResponseData:YES];
    [service setServiceShouldFollowNextLinks:YES];
   [service setUserCredentialsWithUsername:[mUsername stringValue] password:[mPassword stringValue]];

    // GENERATING THE URL
    NSURL *feedURL=[GDataServiceGoogleContact contactFeedURLForUserID:kGDataServiceDefaultUser];
    GDataQuery *contQuery=[GDataQueryContact contactQueryWithFeedURL:feedURL];
    [contQuery setShouldShowDeleted:YES];
    [contQuery setMaxResults:2000];
    GDataServiceTicket *ticket=[service fetchFeedWithQuery:contQuery delegate:self didFinishSelector:@selector(hasFetchedContacts:feed:error:)];    
}


-(void) hasFetchedContacts:(GDataServiceTicket*) ticket  feed:(GDataFeedContact*) contacts error:(NSError*) err
{
    NSArray *contactList=[contacts entries];
    NSLog(@"%d",[list writeToFile:@"/Users/subhranil/Desktop/contactList" atomically:NO]);  

}

3 个答案:

答案 0 :(得分:2)

使用以下命令将其包装到NSData:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:contactList];

然后将NSData保存到文件:

[data writeToFile:@"/Users/subhranil/Desktop/contactList" atomically:NO];

您可以稍后使用以下方法将数据恢复为NSArray:

NSData *data = [NSData dataWithContentsOfFile: @"yourFilePath"];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data]

确保 NSArray内的对象符合NSCoding

答案 1 :(得分:1)

您可以将byte数组用于此目的,并NSData用于写入文件 保存:

NSData *data=[[NSData alloc] initWithBytes:[contacts entries] length:total];
[data writeToFile:@"path" atomically:YES];

total =数组的总大小(以字节为单位)

用于检索:

   NSData *newdata = [NSData dataWithContentsOfFile:@"path"];
   NSUInteger len = [newdata length];
   Byte *byteData = (Byte*)malloc(len);
   memcpy(byteData, [newdata bytes], len);

byteData现在将包含一个GDataEntryContact对象数组,您可以相应地使用它们。

答案 2 :(得分:0)

您可以使用xml作为生成器对GDataObject进行编码/解码。

编码:

[entry setNamespaces:[entry completeNamespaces]];
NSString *xml = [[entry XMLElement] XMLString];
if (nil != xml) 
{
    //Store your xml NSString to a file
}

解码:

NSString *xml = //Read your XML String from file;
NSXMLElement *xmlElement = [[NSXMLElement alloc] initWithXMLString:xml error: &error];
if (!error) {
    return [[GDataEntryDocBase alloc] initWithXMLElement:xmlElement parent: nil];
}