writing NSString type to a file

2019-09-02 00:07发布

问题:


I'm implementing the following function on appdelegate,
but I need to write NSString type instead of typical float values.
Since xcode doesn't allow an object to be in my desired position,
I used char* instead as follows, where as my data to be passed are of type NSString.
As expected, it doesn't work...
How could I manipulate it so that I could write NSString data type?
Should I make some conversion?
Please help me out..

- (void)addHallOfFamer:(char*)newHofer{
    [hofArray addObject:[NSString stringWithFormat:@"%@",newHofer]];
    [hofArray sortUsingSelector:@selector(compare:)];
    NSArray* paths =
    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    NSString* hofArrayPath = [documentsDirectory
                          stringByAppendingPathComponent:@"hofers.plist"];
    [hofArray writeToFile:hofArrayPath atomically:YES];
}

(added) following is how I'm calling the written NSStrings from another view, which doesn't reflect my updating.

MainAppDelegate* delegate;
delegate = (MainAppDelegate*)[[UIApplication sharedApplication] delegate];
NSArray *hofers = [[delegate.hofArray reverseObjectEnumerator] allObjects];
hoferName1.text = [NSString stringWithFormat:@"%@",[hofers objectAtIndex:0]];

回答1:

First, with the current char * argument, you need to use %s as your format directive, not %@.

Second, to use an NSString * as your argument, just add it to hofArray.



回答2:

The easiest solution would be to just save the array in NSUserDefaults. Since it is an array of strings, saving and retrieving it that way should work fine and would be easier than dealing with the iOS filesystem.


Edit: If you really want to save it in the filesystem, look into the NSKeyedArchiver method + (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path and the NSKeyedUnarchiver method + (id)unarchiveObjectWithFile:(NSString *)path.


Edit 2: As ondmike pointed out, you need to use %s rather than %@ for your -stringWithFormat: method call to work properly. Relevant documentation is String Format Specifiers