0

I am a bit stuck on an objective c function and was looking for some help!

This is for an OSX app that pulls in data from twitter as an array, then inserts them into Core Data.

I have a load of objects in Core Data that i want to write to file as some XML, i have a fetch request that filters and returns an array of library objects which i would like to write to disk as XML.

I have been looking at the various libraries and tutorials online and they all seem orientated around reading rather than writing, and the fact it's an array of libraries also seems to complicate matters.

So far i have tried this, but it never seems to create the file, but annoyingly doesn't give me any kind of error either:

-(void)writeTweetsToXML{
//Create new fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];

//Set new predicate to only fetch tweets that have been favourited
NSPredicate *filterFavourite = [NSPredicate predicateWithFormat:@"approved == YES"];

//Setup the Request
[request setEntity:[NSEntityDescription entityForName:@"Tweet"    inManagedObjectContext:_managedObjectContext]];

//Assign the predicate to the fetch request
[request setPredicate:filterFavourite];
NSError *error = nil;

//Create an array from the returned objects
NSArray *tweetsToExport = [_managedObjectContext executeFetchRequest:request error:&error];
NSAssert2(tweetsToExport != nil && error == nil, @"Error fetching events: %@\n%@", [error localizedDescription], [error userInfo]);

//for (id obj in tweetsToExport)
  //NSLog(@"obj: %@", obj);


NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [NSString stringWithFormat:@"%@/tweets.xml", documents];
NSString *writeerror;

if(tweetsToExport) {
    [tweetsToExport writeToFile:path atomically:YES];
    NSLog(@"%@ written to %@", tweetsToExport, path);
}
else {
    NSLog(@"%@",writeerror);

}


}

And this is the structure of the managed objects:

@property (nonatomic, retain) NSString * text;
@property (nonatomic, retain) NSString * userName;
@property (nonatomic, retain) NSString * realName;
@property (nonatomic, retain) NSString * avatarUrl;
@property (nonatomic, retain) NSString * tweetID;
@property (nonatomic, retain) NSNumber * approved;
@property (nonatomic, retain) NSDate * postDate;
@property (nonatomic, retain) NSDecimalNumber * longitude;
@property (nonatomic, retain) NSDecimalNumber * latitude;
@property (nonatomic, retain) NSNumber * profanity;
@property (nonatomic, retain) NSString * otherUserTweet;
@property (nonatomic, retain) NSString * favouriteTweet;

A pointer at any useful info or libraries would be incredibly helpful!

Thanks

Gareth

Edit 1 Ok, have tried re-encoding the array as data, and modified the code a bit to report a success/fail on write, without encoding i was getting a failed write, however the output is now essentially garbage.

Code is now as follows:

    NSDictionary* environ = [[NSProcessInfo processInfo] environment];
BOOL inSandbox = (nil != [environ objectForKey:@"APP_SANDBOX_CONTAINER_ID"]);
NSLog(@"App Sandbox Status = %d", inSandbox);

NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [NSString stringWithFormat:@"%@/tweets.xml", documents];
NSString *writeerror;
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:tweetsToExport];
if(tweetsToExport) {
    BOOL successful = [data writeToFile:path atomically:YES];
    NSLog(@"Success = %d", successful);
}
else {
    NSLog(@"%@",writeerror);

}

However that produces garbage output:

bplist00‘úùX$versionX$objectsY$archiverT$top܆Ø$*+,-./04:FMDRSXfghijknsxÜáàâäãéìòU$null“    
ZNS.objectsV$class£
ÄÄÄÄ#›
      !"#$%&'(^otherUserTweetWtweetIDXrealNameXapprovedYlongitudeXpostDateXlatitudeYavatarUrlYprofan    ityXuserNameTtext^favouriteTweetÄÄÄÄÄÄ  Ä
ÄÄÄÄÄÄ_wPS Myself alongside the mighty @CJbeatz will be co-hosting and DJ for a huge gig      for schools at Wembley Arena this Wed.\TherealNihalWNihal         A_Qhttp://a0.twimg.com/profile_images/1021089851/BB213320_RADIO_1_-   _NIHAL_normal.jpg_353964930917085186“1
 23WNS.time#A∑ⲶÄ
“5678Z$classnameX$classesVNSDate¢79XNSObject◊
;<=>?    @ABCD/DC[NS.mantissa[NS.negative[NS.exponent^NS.mantissa.boYNS.lengthZNS.compactÄO“56GH_NSDeci    malNumberPlaceholder•IJKL9_NSDecimalNumberPlaceholder_NSDecimalNumberXNSNumberWNSValue◊
;<=>?@AOCD/DCÄORNO“56TUUTweet£VW9UTweet_NSManagedObject›
Z[ ]^_`%b'dÄÄÄÄÄÄÄÄÄÄÄÄÄ_"Bird. Bath. http://t.co/1PLF2gKI4T[DerrenBrown\Derren     Brown_Zhttp://a0.twimg.com/profile_images/3682019430/d4636e8301b238c6a10c55efacd2442c_normal.j     peg_353965570888192000“1
l3#A∑âˇ@Ä
◊
;<=>?@ApCD/DCÄO◊
;<=>?@AuCD/DCÄO›
z{ }~Ä%Ç'ÑÄÄÄÄÄ!Ä Ä"ÄÄÄÄÄÄ_âThe Surgery with myself and new resident Doctor @DrRadhaModgil     starts at 9pm on @BBCR1 It's a Summer Special - 03700100100, Text on 81199Sahj_Aled Haydn     Jones_Mhttp://a0.twimg.com/profile_images/2254837339/Aled-012_-        _Version_3_normal.jpg_353965267564507138“1
å3#A∑â˛ˆÄ
◊
;<=>?@AêCD/DCÄO◊
;<=>?@AïCD/DCÄO“56ôö^NSMutableArray£ôõ9WNSArray_NSKeyedArchiver—ûüTrootÄ#-27^dit{ÅÉÖᢠ   ±π¬À’fiÁÒ˚  "$&(*,.02¨π¡*,19BDIT]dgpãó£≤º«…‹›fl‡Â%7@HWYlmnqv|ÄÜò≥µ∑πªΩø¡√≈«…ÀÕÚ˛h}Çãçúû    ±≤≥¬ƒ◊ÿŸÙˆ¯˙¸˛
öû±$&57JKL[]pqrwÜäí§ß¨†Æ

Edit 2

Ok, so, if i open this file in a suitable viewer (BBEdit) it is formatted ok, but it's not really very useful, all i want to be able to do is encode the objects with there values into XML, any help greatly appreciated.

4

1 回答 1

0

您的第一次尝试失败了,因为writeToFile:atomically:仅适用于属性列表类型NSString—— 、NSNumberNSDataNSDateNSArrayNSDictionaryNSManagedObject不在列表中,您可能创建的任何子类也不在列表中。您不是在尝试编写字典数组——您是在尝试编写托管对象数组。

转换NSData和写入工作,但你得到的是一个二进制属性列表。它不是垃圾,它是该代码的预期格式,但它的设计目的不是为了人类可读。

如果您使用了原始代码,但在执行提取之前添加了此代码:

[request setResultType:NSDictionaryResultType];

...你会得到你能得到的东西writeToFile:atomically:

于 2013-07-11T17:19:44.250 回答