开发者

Having a problem with reading a file using NSString initWithContents OfFile

In this program when I debug, it is showing the nil for fileNameString. I could not understand what is the problem. Please help me ?

@implementation fromFileRead1
NSString *fileNameString;

-(id)init
{
    if( (self = [super init]) ) 
    {
        fileNameString = [[NSString alloc] initWithContentsOfFile: @"enemyDetails.rtf" encoding:NSUTF8StringEncoding error:nil];
        NSArray *lines = [fileNameString componentsSeparatedByString:@"\n"]; 
        for (id *line in lines)
        {
            NSLog(@"Line1%@", line );
        }
    }
    return self;
}
@end

Thank You.


-(id)init
{
    if( (self = [super init]) ) 
    {
        NSString *path = @"/Users/sridhar/Desktop/Projects/exampleOnFile2/enemyD开发者_运维百科etals.txt";
        NSString *contentsOfFile = [[NSString alloc] initWithContentsOfFile:path];
        NSArray *lines = [contentsOfFile componentsSeparatedByString:@"\n"]; 
        for (id *line in lines)
        {
            NSLog(@"Line1%@", line );
        }
    }
    return self;
}
@end


You need to specify the full path to the file with string so the problem must be with this part:

... initWithContentsOfFile: @"enemyDetails.rtf" ...

What exactly path you need depends on where you store your text file. If it is a resource in your bundle you can get the path using -pathForResource: function from NSBundle:

NSString *fPath = [[NSBundle mainBundle] pathForResource:@"enemyDetails" ofType:@"rtf"];

If it is stored in another directory in your applications sandbox - see Getting Paths to Application Directories section in "Developer Programming Guide" about how to get paths for them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜